Formatting a number with exactly two decimals in JavaScript

后端 未结 30 2343
广开言路
广开言路 2020-11-21 06:29

I have this line of code which rounds my numbers to two decimal places. But I get numbers like this: 10.8, 2.4, etc. These are not my idea of two decimal places so how I can

30条回答
  •  我寻月下人不归
    2020-11-21 07:01

    To format a number using fixed-point notation, you can simply use the toFixed method:

    (10.8).toFixed(2); // "10.80"
    
    var num = 2.4;
    alert(num.toFixed(2)); // "2.40"
    

    Note that toFixed() returns a string.

    IMPORTANT: Note that toFixed does not round 90% of the time, it will return the rounded value, but for many cases, it doesn't work.

    For instance:

    2.005.toFixed(2) === "2.00"

    UPDATE:

    Nowadays, you can use the Intl.NumberFormat constructor. It's part of the ECMAScript Internationalization API Specification (ECMA402). It has pretty good browser support, including even IE11, and it is fully supported in Node.js.

    const formatter = new Intl.NumberFormat('en-US', {
       minimumFractionDigits: 2,      
       maximumFractionDigits: 2,
    });
    
    console.log(formatter.format(2.005)); // "2.01"
    console.log(formatter.format(1.345)); // "1.35"

    You can alternatively use the toLocaleString method, which internally will use the Intl API:

    const format = (num, decimals) => num.toLocaleString('en-US', {
       minimumFractionDigits: 2,      
       maximumFractionDigits: 2,
    });
    
    
    console.log(format(2.005)); // "2.01"
    console.log(format(1.345)); // "1.35"

    This API also provides you a wide variety of options to format, like thousand separators, currency symbols, etc.

提交回复
热议问题