作者热门文章
- Java 双重比较
- java - 比较器与 Apache BeanComparator
- Objective-C 完成 block 导致额外的方法调用?
- database - RESTful URI 是否应该公开数据库主键?
我想将 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/
我是一名优秀的程序员,十分优秀!