brno792 brno792 - 6 months ago 23
Javascript Question

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.

Answer Source
var val = Math.round(Number(n) *100) / 100;
var parts = val.toString().split(".");
var num = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",") + (parts[1] ? "." + parts[1] : "");