我正在尝试将 Double 值四舍五入到小数点后两位:
变量 x = 0.68999999999999995 var roundX = round(x * 100.0)/100.0 println(roundX)//打印 0.69
如果 print 值是正确的..但是 var 值不是我期望的,继续 0.68999999999999995
我需要 Double 值...而不是像其他 StackOverflow 答案那样的 String :(
最佳答案
像 double 这样的 float 没有小数位数。它们以二进制形式存储值,无法准确表示像 .69 这样的值。这只是计算机上二进制 float 的性质。
使用数字格式化程序,或按照@KRUKUSA 的建议使用 String(format:)
var x:Double = 0.68999999999999995
let stringWithTwoDecimals = String(format: "%.2f", x)
println(stringWithTwoDecimals)
关于ios - 圆形功能无法按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31011875/