miOS
miOS

Reputation: 1377

Decimal Round Off issue in Swift

I am using default decimal to string converter with rounded off values using provision provided by Apple.

String(format: "%.02f", 0.345)

But if I round off 0.345 getting 0.34 value where as if I round off 0.445 getting 0.45.

Is this a bug in SDK or it's a expected behaviour?

Note: I know the alternate solution is using NumberFormatter but want to check issue with String formatter.

Upvotes: 1

Views: 152

Answers (1)

New Dev
New Dev

Reputation: 49590

This is an artifact of floating point binary representation.

The decimals 0.345 and 0.445 cannot be precisely represented as a floating point binary number. So, the actual value is very close, but not quite the same.

Specifically, a double-precision 0.345 is actually .3449999...., and a double-precision 0.445 is actually 0.4450000000000000066613....

Hence the result you're getting.

Upvotes: 2

Related Questions