在swift中将双精度值四舍五入到x个小数位数 [英] Rounding a double value to x number of decimal places in swift
问题描述
谁能告诉我如何在 Swift 中将 double 值四舍五入到 x 位小数?
Can anyone tell me how to round a double value to x number of decimal places in Swift?
我有:
var totalWorkTimeInHours = (totalWorkTime/60/60)
totalWorkTime
是秒内的 NSTimeInterval(双精度).
With totalWorkTime
being an NSTimeInterval (double) in second.
totalWorkTimeInHours
会给我小时数,但它给了我这么长的精确数字的时间量,例如1.543240952039......
totalWorkTimeInHours
will give me the hours, but it gives me the amount of time in such a long precise number e.g. 1.543240952039......
当我打印 totalWorkTimeInHours
时,如何将其舍入到 1.543?
How do I round this down to, say, 1.543 when I print totalWorkTimeInHours
?
推荐答案
你可以使用 Swift 的 round
函数来完成这个.
You can use Swift's round
function to accomplish this.
要将 Double
以 3 位精度舍入,首先将其乘以 1000,然后将其舍入并将舍入后的结果除以 1000:
To round a Double
with 3 digits precision, first multiply it by 1000, round it and divide the rounded result by 1000:
let x = 1.23556789
let y = Double(round(1000 * x) / 1000)
print(y) /// 1.236
与任何一种printf(...)
或 String(format: ...)
解决方案不同,此操作的结果仍然是 类型双重
.
Unlike any kind of printf(...)
or String(format: ...)
solutions, the result of this operation is still of type Double
.
关于有时不起作用的评论,请阅读:每个程序员应该了解的关于浮点运算的知识一个>
这篇关于在swift中将双精度值四舍五入到x个小数位数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!