I have a string n
which is a number.
The following adds the commas where needed, but I also want to change the number of decimals. It should also round where appropriate.
var parts = n.split(".");
var num = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",") + (parts[1] ? "." + parts[1] : "");
This turns a number like 1234.567
in to 1,234.567
.
But I need my number to look like: 1,234.57
I tried taking parts[1]
and converting to a Number, then rounding, then concatenating it back; but that is error prone.
How can I get this result by altering my regex? Thanks.
To limit the number of digits up to 2 places after the decimal, the toFixed() method is used. The toFixed() method rounds up the floating-point number up to 2 places after the decimal.
Using toLocaleString() method The JavaScript toLocaleString() method is used to convert the elements of the given array into a string, and these Strings are separated by a comma ",".
To comma-separate thousands in a big number in JavaScript, use the built-in toLocaleString() method. It localizes the number to follow a country-specific number formatting. To separate thousands with commas, localize the number to the USA.
The toFixed() method in JavaScript is used to format a number using fixed-point notation. It can be used to format a number with a specific number of digits to the right of the decimal. The toFixed() method is used with a number as shown in the above syntax using the '. ' operator.
Edit: Sept 18, 2019
Since new APIs are available, thought it would be helpful to point out that you can do this much more simply using toLocaleString
options:
const numbers = [1, 1000, 2345.67, 21589.334719999995];
const options = {
minimumFractionDigits: 2,
maximumFractionDigits: 2
};
numbers.forEach(num => {
const formatted = Number(num).toLocaleString('en', options);
console.log(formatted);
});
original answer
To add the commas, you could use:
n = parseFloat(n).toFixed(2)
var withCommas = Number(n).toLocaleString('en');
Here is a fiddle
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With