Skip to content

JavaScript decimal precision

  • by

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.


No decimal places

const removedDecimal = Math.round(decimal);

JavaScript decimal precision

Simple example code.

<!DOCTYPE html>
    let money = 160;

    var res = money.toFixed(2);


JavaScript decimal precision

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.

    pi = 3.14159265359;
    twoPlaces = pi.toPrecision(2);
    fivePlaces = pi.toPrecision(5);

    console.log(twoPlaces); // 3.1
    console.log(fivePlaces); // 3.1416

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

Leave a Reply

Your email address will not be published. Required fields are marked *