How to get a decimal portion of a number with JavaScript?

In JavaScript, you can extract the decimal portion of a number using several methods. The most common approach is using the modulo operator (%) with 1.

Using the Modulo Operator (%)

The % operator returns the remainder after division. When used with 1, it gives the decimal part:

<!DOCTYPE html>
<html>
  <body>
    <script>
      var num1 = 5.3;
      var num2 = 4.2;
      var num3 = 8.6;

      document.write(num1 % 1);
      document.write("<br>" + num2 % 1);
      document.write("<br>" + num3 % 1);
    </script>
  </body>
</html>
0.2999999999999998
0.20000000000000018
0.5999999999999996

The Floating-Point Precision Issue

Notice the output shows floating-point precision errors. This is because JavaScript uses IEEE 754 standard for numbers, which can't represent some decimals exactly.

Using Math.floor() for Clean Results

To avoid precision issues, subtract the integer part using Math.floor():

<!DOCTYPE html>
<html>
  <body>
    <script>
      var num1 = 5.3;
      var num2 = 4.2;
      var num3 = 8.6;

      document.write(num1 - Math.floor(num1));
      document.write("<br>" + (num2 - Math.floor(num2)));
      document.write("<br>" + (num3 - Math.floor(num3)));
    </script>
  </body>
</html>
0.2999999999999998
0.20000000000000018
0.5999999999999996

Rounding for Display

For display purposes, round the result to avoid precision issues:

<!DOCTYPE html>
<html>
  <body>
    <script>
      var num1 = 5.3;
      var num2 = 4.2;
      var num3 = 8.6;

      document.write(Math.round((num1 % 1) * 10) / 10);
      document.write("<br>" + Math.round((num2 % 1) * 10) / 10);
      document.write("<br>" + Math.round((num3 % 1) * 10) / 10);
    </script>
  </body>
</html>
0.3
0.2
0.6

Comparison of Methods

Method Syntax Handles Precision?
Modulo operator number % 1 No
Math.floor subtraction number - Math.floor(number) No
Rounded result Math.round((number % 1) * 10) / 10 Yes

Conclusion

Use number % 1 to get the decimal portion of a number. For clean display results, round the output to handle JavaScript's floating-point precision issues.

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

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements