Formatting a number with exactly two decimals in JavaScript

后端 未结 30 2227
广开言路
广开言路 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 06:42

    toFixed(n) provides n length after the decimal point; toPrecision(x) provides x total length.

    Use this method below

    // Example: toPrecision(4) when the number has 7 digits (3 before, 4 after)
        // It will round to the tenths place
        num = 500.2349;
        result = num.toPrecision(4); // result will equal 500.2
    

    AND if you want the number to be fixed use

    result = num.toFixed(2);
    

提交回复
热议问题