How do you round a number to N decimal places

You need to realize that there is a difference between rounding for output, which you can do with String.format and other methods and having a value that exactly equals 3.14. If you use the double type you will NEVER, EVER have a value that exactly equals 3.14. Even if you have a statement like:

val a = 3.14

The variable a does not actually equal the value 3.14 exactly. It actually equals 3.140000000000000124344978758017532527446746826171875 [Edit: I originally said 3.1400001049041748046875 which is the exact value of the float value 3.14f].

If you want a value that exactly equals 3.14 the ONLY way to get it (for the JVM) is with BigDecimal.

4 Likes