Skip to content

JavaScript format number 2 decimals without rounding | Example code

  • by

Use Math floor and some additional arithmetics to format number 2 decimals without rounding in JavaScript. Another way is to convert the number into a string, match the number up to the second decimal place and turn it back into a number.

Math.floor(15.7784514000 * 100) / 100

Or

Number(15.7784514000.toString().match(/^\d+(?:\.\d{0,2})?/))

Example format number 2 decimals without rounding in JavaScript

Simple example code using math floor.

<!DOCTYPE html>

<body>
  <script>
   var numb = 123.239454;
   var res = Math.floor(numb * 100) / 100

   console.log(res)
 </script>
</body>
</html>

Output:

JavaScript format number 2 decimals without rounding

More example

var num1 = Math.floor(15.7784514000 * 100) / 100;
console.log(num1);

var num2 = Number(15.7784514000.toString().match(/^\d+(?:\.\d{0,2})?/));
console.log(num2)
console.log(num2.toFixed(2))

Source: stackoverflow.com

Do comment if you have any doubts or suggestions on this JS format code.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading