0

right now i have this regex to return numbers with formatted digits.

function formatCurrency(amount) {
    var amt = ""+amount;
    return amt.replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,");
}

The result for any provided number is coming as Due: $1,944.5. But I need to add two digits after decimal i., it should come as Due: $1,944.50. Please help me with the correct regex to add two digits after decimal points. Thanks for your help.

3 Answers3

1

If you're just formatting the number to have 2 decimal places regex seems to be overkill you could just use the following:

return amount.toFixed(2);

unless there's a specific reason you absolutely have to use regex?

Mellyn
  • 26
  • 2
0

If you want to add the trailing zero with a regex, you can do it like this;

function formatCurrency(amount) {
    var amt = ""+amount;
    amt = amt.replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,");
    return amt.replace(/(\.\d{1})$/, "$1"+"0");
}

fiddle

To ensure that there are always 2 figures after the decimal point, even when there are no cents, you can use .toFixed(2) before applying your regex.

function formatCurrency(amount) {
    // Ensures there are 2 decimal places
    var amt = parseFloat(amount).toFixed(2); 
    // Add commas for every block of 3 digits
    return amt.replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,");
}

fiddle

James Newton
  • 6,623
  • 8
  • 49
  • 113
  • This works but if there is no decimal it does not adds two zeroes. Please help me to add two zeroes after a decimal if there is no digits after period.For example if I provide $1500 it should come as $1,500.00. Right now its coming as $1,500. – Jquery Developer Nov 05 '14 at 19:21
  • I've updated my answer, to show you how to integrate the '.toFixed(2)` technique with your own regex. – James Newton Nov 05 '14 at 22:13
0

You don't need to use regex for this operation.

function formatCurrency(amount) {
    return parseFloat(amount).toFixed(2);
}

Now, this will only work for western currencies.

amphetamachine
  • 27,620
  • 12
  • 60
  • 72