gpt4 book ai didi

swift - 四舍五入到小数点后一位(舍去小数位)

转载 作者:搜寻专家 更新时间:2023-11-01 07:05:16 24 4
gpt4 key购买 nike

我想将 double 四舍五入到小数点后一位。例如,如果我有一个双 let val = 3.1915,我想将其四舍五入为 3.1。正常的舍入函数会将其舍入到 3.2 但我基本上只想删除剩余的小数位。做这个的最好方式是什么?有这个的 native 功能吗?我知道这很简单,但我想知道最好的方法是在我不使用任何变通方法或不良做法的情况下。这不是其他舍入问题的重复,因为我不是在询问舍入问题,而是在询问如何舍弃小数位。

同样,如果值为3.1215,它也会四舍五入为3.1

最佳答案

使用函数 trunc()(代表截断),它会去掉小数部分而不四舍五入。具体来说,将 Double 值乘以 10,截断它,然后再次除以 10。然后,要使用 1 位小数显示,请使用 String(format:):

let aDouble = 1.15
let truncated = trunc(aDouble * 10) / 10
let string = String(format: "%.1f", truncated
print(string)

(displays "1.1")

或者,处理整个样本值数组:

让 floats = stride(from: 1.099, to: 2.0, by: 0.1)

let truncs = floats
.map { trunc($0 * 10) / 10 }
.map { String(format: "%.1f", $0) }

let beforeAndAfter = zip(floats, truncs)
.map { (float: $0.0, truncString: $0.1)}

beforeAndAfter.forEach { print(String(format: "%.3f truncated to 1 place is %@", $0.0, $0.1)) }

输出:

1.099 truncated to 1 place is 1.0
1.199 truncated to 1 place is 1.1
1.299 truncated to 1 place is 1.2
1.399 truncated to 1 place is 1.3
1.499 truncated to 1 place is 1.4
1.599 truncated to 1 place is 1.5
1.699 truncated to 1 place is 1.6
1.799 truncated to 1 place is 1.7
1.899 truncated to 1 place is 1.8
1.999 truncated to 1 place is 1.9

关于swift - 四舍五入到小数点后一位(舍去小数位),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48455402/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com