JavaScript decimal precision

Use JavaScript Number toFixed() to convert a number to a string of decimals. The number of decimal places in float values can be set using the toFixed() method.

``number.toFixed(x)``

No decimal places

``const removedDecimal = Math.round(decimal);``

JavaScript decimal precision

Simple example code.

``````<!DOCTYPE html>
<html>
<body>
<script>
let money = 160;
console.log(money);
console.log(typeof(money));

var res = money.toFixed(2);
console.log(res);
console.log(typeof(res));
</script>
</body>
</html>
``````

Output:

JavaScript force precision to 2 decimal numbers

``````// To force decimal to use only two numbers after coma, you can use this
var numberOne = 4.05;
var numberTwo = 3;

// Output
var total = numberOne * numberTwo; // This will be 12.149999999999999

// Use this :
var total = Number(numberOne * numberTwo).toFixed(2); // This will be 12.15``````

Using toPrecision() Method

This method converts the number into a string, keeping the total number of digits of the value as specified and rounding them to the nearest number.

``````<script>
pi = 3.14159265359;
twoPlaces = pi.toPrecision(2);
fivePlaces = pi.toPrecision(5);

console.log(twoPlaces); // 3.1
console.log(fivePlaces); // 3.1416
</script>``````

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

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

OS: Windows 10

Code: HTML 5 Version