Formatting a number with exactly two decimals in JavaScript

后端 未结 30 2286
广开言路
广开言路 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:59

    Here is my 1-line solution: Number((yourNumericValueHere).toFixed(2));

    Here's what happens:

    1) First, you apply .toFixed(2) onto the number that you want to round off the decimal places of. Note that this will convert the value to a string from number. So if you are using Typescript, it will throw an error like this:

    "Type 'string' is not assignable to type 'number'"

    2) To get back the numeric value or to convert the string to numeric value, simply apply the Number() function on that so-called 'string' value.

    For clarification, look at the example below:

    EXAMPLE: I have an amount that has upto 5 digits in the decimal places and I would like to shorten it to upto 2 decimal places. I do it like so:

    var price = 0.26453;
    var priceRounded = Number((price).toFixed(2));
    console.log('Original Price: ' + price);
    console.log('Price Rounded: ' + priceRounded);

提交回复
热议问题