0

I'm trying to round decimal number to 2 decimals and I'm using String(format:"%.2f", number) to achieve that.

Problem is that it is not consistent and sometimes it rounds number wrong.

For example it rounds 2.345 to 2.35 as it should, but it rounds 1.345 to 1.34 which is wrong, it should be 1.35.

Does anyone know why is this happening and how to fix it?

Mdev
  • 1
  • 2
  • 1
    There there is no such Double as `1.345`. The closest Double is 1.344999999999999973, which correctly is displayed as 1.34. (You can see this with `String(format:"%.18f", 1.345)`.) If you need precise decimal values rather than binary values, you need to use Decimal, not Double. See https://stackoverflow.com/questions/588004/is-floating-point-math-broken – Rob Napier Jan 09 '23 at 18:15

0 Answers0