swift Double rounds up to five odd and double

The official end of rounding to five odd and even is as follows: The rule of "rounding five odd and even": that is, look at the digit after the significant figure to be retained. If it is greater than 5, move forward by one, and if it is less than 4, round it .Equal to 5, then look after 5, if not all 0 after 5, then add one digit. After 5 is all zero, look at the front of 5, if it is odd, add 1, if it is even, discard it.
But it seems that in swift Not so, let me give an example:

class func doubleToString(value:Double,point:Int)->String{
      return   NSString(format: "%.\(point)f", value) as String
    }

print(Common.doubleToString(12.6225, point: 3)) //12.623
print(Common.doubleToString(12.6215, point: 3)) //12.621 The
comment followed by the print value seems to be different from the defined rules.

Then, there is another strange phenomenon:
var sum:Double = 0
The following values ​​are: 13.51, 11.51, 12.51, 13.51, because three decimal places need to be reserved uniformly, so I use the above method in a frenzy to put these The data is converted to "13.510", "11.510", "12.510", "13.510"
and then sum = sum + Double(v)!
and then let s = Common.doubleToString(sum/4.0, point: 3)
After countless cycles, the answer actually appears to be 12.623 / 12.622 alternately appear randomly.
The answer obtained by printing sum/4.0 is 12.6225, the result printed by direct printing of Common.doubleToString(12.6225, point: 3) is always 12.623, and the result printed by direct printing of Common.doubleToString(50.49/4.0, point: 3) It is also still sticking to 12.623, and there is no random situation. So, I began to speculate that since sum and 50.49 have different results, it means that the two values ​​are not completely equal, so where is the most likely difference is the retention of decimal places.
So take the following way:

let st = Common.doubleToString(sum, point: 3)
let s = Common.doubleToString(Double(st)!/Double(c), point: 3)

Sure enough, the answer is always 12.623, and there is no random phenomenon.
I can't explain this matter, first write it down, and then revise it later when I have new insights.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325753176&siteId=291194637