Search code examples
javascriptnumberscurrencycryptocurrency

How to make a number with proper commas round to exactly 2 decimal places?


In my code, I am trying to have a calculator that converts different currencies using Javascript. I would like the final result to be in a form with proper commas in the United States form, so for example, if the number was 1000000.3 I would want it to display as 1,000,000.30

I have tried using toFixed, toLocaleString, and parseFloat, using toFixed to round to 2 decimal places, toLocaleString to make the proper comma formatting, and parseFloat to convert the toFixed and toLocaleString to a number so that they can operate on each other.

The problem is that when I use toFixed and then toLocaleString, toFixed would make the original number 1000000.30, but then toLocaleString would get rid of the last 0 making the end result 1,000,000.3. Alternatively, when I tried reversing the order and using toLocaleString and then toFixed, toLocaleString makes it 1,000,000.3, but then toFixed treats the first comma as a decimal, making the end result 1,000 instead of 1,000,000.30. Is there anything that I am missing or a different strategy to do this that I don't know about? I'm quite new to coding so all suggestions are welcome :)

(the output of the below code can be seen here: https://xrpalerts.000webhostapp.com/testing_ground.html)

<!DOCTYPE html>
<html>
<body>

<script>

var CalculatorResult = 1000000.3
var CalculatorResultLocale = parseFloat(CalculatorResult).toLocaleString("us-EN");
var CalculatorResultLocaleFixed = parseFloat(CalculatorResultLocale).toFixed(2);

document.write(CalculatorResultLocale);
</script>
<br>

<script>
document.write(CalculatorResultLocaleFixed);
</script>
<br>
<br>
<script>
var CalculatorResultFixed = parseFloat(CalculatorResult).toFixed(2);
var CalculatorResultFixedLocale = parseFloat(CalculatorResultFixed).toLocaleString("us-EN");

document.write(CalculatorResultFixed);
</script>
<br>
<script>
document.write(CalculatorResultFixedLocale);
</script>



</body>
</html>

Solution

  • You can do it like this

    var formatter = new Intl.NumberFormat('en-US', {
      style: 'currency',
      currency: 'USD',
    });
    var num1 = 1000000.3
    console.log(formatter.format(num1))