donchan
donchan

Reputation: 357

Strange behavior when formatting string to number for Swift

The behavior of str1 and str2 that is different.
I expected that str2 is 15.4.
Why?

let str1 = String(format: "%.1f", Double("12.55")!) // 12.6
let str2 = String(format: "%.1f", Double("15.35")!) // 15.3

Upvotes: 1

Views: 138

Answers (1)

matt
matt

Reputation: 535915

You're hitting an issue having to do with how numbers are stored in a computer. But you are basically writing C code, which is not a good thing to do in Swift. For better consistency in rounding behavior, use a NumberFormatter:

let f = NumberFormatter()
f.maximumFractionDigits = 1
let str1 = f.string(from: 12.55)!
let str2 = f.string(from: 15.35)!
print(str1, str2) // 12.6 15.4

Upvotes: 3

Related Questions