# Rounding float numbers to two decimals

#1

I had students build a coin flipping simulation and at the end I wanted them to give the percentage of each option. However when it displays the number, it creates values like for example 53.25678900004. I would like to reduce that to only display two decimals. Math.round() will round to an integer and I would like better than that. Any ideas?

#2

try the toFixed function. Here is an example: https://www.w3schools.com/jsref/jsref_tofixed.asp

#3

Thank you so much. I guess I was under the assumption that only code.org’s limited javascript commands would work on here. Thank you for showing me that other functions will work as well!

#4

Not all functions work. Some do!

#5

If you wanted to demonstrate an algorithm that lets you do this without resorting to introducing toFixed you can use this technique:

1. multiply the number by the power of ten equal to the number digits after the decimal that you want to keep
2. Then call round()
3. Then divide the number by the value that you used in step 1.

for example, to round to 2 decimal digits : Math.round(100 * 53.25678900004) / 100 results in 53.26

#6

Actually I didn’t even think about that. But it makes perfect sense. Thanks!