How to deal with floating point number precision in JavaScript?

Floating point precision issues occur when JavaScript cannot exactly represent certain decimal numbers in binary format. Common problems include 0.1 + 0.2 = 0.30000000000000004. JavaScript provides several methods to handle these precision issues.

The Floating Point Problem

JavaScript uses IEEE 754 double-precision floating-point format, which can cause unexpected results:

<!DOCTYPE html>
<html>
  <body>
    <script>
      console.log(0.1 + 0.2);           // 0.30000000000000004
      console.log(0.1 + 0.2 === 0.3);  // false
      console.log(9.7 * 100);          // 969.9999999999999
    </script>
  </body>
</html>
0.30000000000000004
false
969.9999999999999

Using toPrecision()

The toPrecision() method formats a number to a specified total number of significant digits:

<!DOCTYPE html>
<html>
  <body>
    <script>
      var num = 28.6754;
      document.write(num.toPrecision(3) + "<br>");
      document.write(num.toPrecision(2) + "<br>");
      document.write(num.toPrecision(5));
    </script>
  </body>
</html>
28.7
29
28.675

Using toFixed()

The toFixed() method formats a number to a specified number of decimal places:

<!DOCTYPE html>
<html>
  <body>
    <script>
      var result = 0.1 + 0.2;
      document.write("Original: " + result + "<br>");
      document.write("Fixed to 1 decimal: " + result.toFixed(1) + "<br>");
      document.write("Fixed to 2 decimals: " + result.toFixed(2));
    </script>
  </body>
</html>
Original: 0.30000000000000004
Fixed to 1 decimal: 0.3
Fixed to 2 decimals: 0.30

Using Math.round() with Multipliers

Round to a specific number of decimal places using Math.round():

<!DOCTYPE html>
<html>
  <body>
    <script>
      function roundTo(num, decimals) {
        var multiplier = Math.pow(10, decimals);
        return Math.round(num * multiplier) / multiplier;
      }
      
      var result = 0.1 + 0.2;
      document.write("Original: " + result + "<br>");
      document.write("Rounded: " + roundTo(result, 2));
    </script>
  </body>
</html>
Original: 0.30000000000000004
Rounded: 0.3

Comparison of Methods

Method Purpose Return Type
toPrecision() Total significant digits String
toFixed() Decimal places String
Math.round() Mathematical rounding Number

Conclusion

Use toFixed() for decimal places, toPrecision() for significant digits, and Math.round() with multipliers when you need numeric results. Choose the method based on your specific precision requirements.

Updated on: 2026-03-15T23:18:59+05:30

991 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements