print(String(format: "%.2f", 1.255)) => 1.25

print(String(format: "%.2f", 1.255)) => 1.25

print(String(format: "%.2f", 1.256)) => 1.26

It's not rounded ?? Or am I missing something ??

You are probably running into the binary floating point representation limits. Float/Double won't always round the way you expect. If that matters for your application, you should look at using Decimal numbers. It doesn't eliminate rounding problems, but they will behave more like you would expect.

Why should 1.25 yields 1.26 more than 1.25, it is just in the middle and 1.25 is considered the closest value (1.25 and 1.26 are at the same distance, they made this choice).

        print(String(format: "%.2f", 1.255001))

print 1.26

I do not see what the issue is.

You could use an extension on Double, like I do when I'm displaying prices, e.g.:

extension Double {
    func rounded(toPlaces places: Int) -> Double {
        let divisor = pow(10.0, Double(places))
        return (self * divisor).rounded() / divisor
    }
}

Then use it like this:

print(1.256.rounded(toPlaces: 2))

It's not about being rounded. It's about suppressing everything after the 2nd decimal place using the format specifier %.2f if you wanted to show the nth position after the decimal place then %.3f will show 1.255, %.5f will show 1.25500 etc etc.

1.255 will not round because there is nothing carry over. 1.256 will round because there is a 1 to carry over.

print(String(format: "%.2f", 1.255)) => 1.25
 
 
Q