0
let amount:Float = 2.235
print("\(roundf(self.amountTax * 100) / 100)")

it returns 2.23

but it should be 2.24

Eeshwar
  • 277
  • 3
  • 17
Ranjan
  • 95
  • 9
  • 1
    Try `print(amount.debugDescription)` and you'll see the problem ... – Martin R Nov 08 '16 at 13:19
  • 2
    Also have a look at [Is floating point math broken?](http://stackoverflow.com/questions/588004/is-floating-point-math-broken) and [What Every Computer Scientist Should Know About Floating-Point Arithmetic](http://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html). – Martin R Nov 08 '16 at 13:25

1 Answers1

1

The result is 2.23 because amount * 100 is 223.5 and the rounding of that is 223 (because 2.235 probably has no exact representation, but is something like 2.234999999999) , and divided by 100 it results in 2.23.

You may want to use the ceilf unction instead:

print("(ceilf(amount * 100) / 100)")

This playground result may give you more understanding: enter image description here

Daniel
  • 20,420
  • 10
  • 92
  • 149