Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

regex format string number with commas and 2 decimals in javascript

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.

like image 215
brno792 Avatar asked Aug 04 '14 20:08

brno792


People also ask

How do I get 2 decimal places in JavaScript?

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.

How do you convert a number to a comma separated string?

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 ",".

How do you print a number with commas as thousands separators in JavaScript?

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.

How do you format numbers in JavaScript?

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.


1 Answers

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

like image 123
Rob M. Avatar answered Oct 28 '22 03:10

Rob M.