let s = Common.doubleToString(sum/Double(count), point: 3)
var a = sum/Double(count)
print(sum) //50.49
print(Double( count)) //4.0
print(a) //12.6225
print(Common.doubleToString(12.6225, point: 3)) //12.623
print(s) //12.622 //12.623 这两个 值居然随机出现了,诡异不?
class func doubleToString(value:Double,point:Int)->String{
return NSString(format: “%.\(point)f”, value) as String
}
var a = sum/Double(count)
print(sum) //50.49
print(Double( count)) //4.0
print(a) //12.6225
print(Common.doubleToString(12.6225, point: 3)) //12.623
print(s) //12.622 //12.623 这两个 值居然随机出现了,诡异不?
class func doubleToString(value:Double,point:Int)->String{
return NSString(format: “%.\(point)f”, value) as String
}
print(s) 得到的值居然是随机的,完全蒙了,问一下有没有懂的同学给解释解释,同时该怎么避免呢?
根据 四舍六入五成双的原则,直接传递12.6225,返回12.623是正确的,但是为什么s是随机的呢?
ps: let b = sum/Double(c) Common.doubleToString(b, point: 3) 得到的值也是随机的出现
let c = 12.6225 Common.doubleToString(c, point: 3) 得到的值是12.623
全部本人认为是不是sum 或 count的保留位数对答案有影响,麻烦懂得同学指点,不胜感激!
解决方案
20
用你代码运行了下,没法重现你的问题
sum: 50.49 ,count: 4.0
12.6225
12.623
12.623
sum: 50.49 ,count: 4.0
12.6225
12.623
12.623
20
假如要解释这个问题,就需要了解浮点数的表示和范围
你可以看看这个博客
http://blog.csdn.net/hyforthy/article/details/19649969
你可以看看这个博客
http://blog.csdn.net/hyforthy/article/details/19649969