brno792 brno792 - 9 months ago 28
Javascript Question

regex format string number with commas and 2 decimals in javascript

I have a string

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
in to
But I need my number to look like:

I tried taking
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] : "");
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download