2

The server provides JSON containing a string such as 1234567.89.

How do I convert it to $ 1,234,568?

Based on How can I format numbers as money in JavaScript?, I can convert it to $ 1,234,567.89.

return "$ " + parseFloat(n).toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, "$1,");

While not perfect because it rounds down versus rounds to nearest dollar, I would have thought the following would work, but it does not:

return "$ " + parseFloat(n).toFixed(0).replace(/(\d)(?=(\d{3})+\.)/g, "$1,");

I also unsuccessfully tried the following:

return "$ " + Math.round(parseFloat(n)).replace(/(\d)(?=(\d{3})+\.)/g, "$1,");
Community
  • 1
  • 1
user1032531
  • 24,767
  • 68
  • 217
  • 387

2 Answers2

3
function roundToDollars(n) { 
    return "$ " + 
        parseFloat(n).toFixed(0)
            .replace(/(\d)(?=(\d{3})+$)/g, "$1,"); 
}

Note that I don't think the function you're asking for is a good idea:

  • you're using (imprecise) floats for decimal arithmetic.
  • and your input here - "n" - is a string, when it really isn't a string.
  • it sounds to me like the "format number" and "prepend $" and "round to nearest" bits are all orthogonal, and a cleaner API wouldn't stick this in one function.

Incidentally, all I changed from your example was the "terminator" detection - since the amount is be rounded, I'm not looking for a dot (\.), but simply the end of the string ($). To be compatible with both, you could use the regex /(\d)(?=(\d{3})+(\.|$))/g.

Eamon Nerbonne
  • 47,023
  • 20
  • 101
  • 166
1

Try this:

function formatNumber(val){

    val = Math.round(parseFloat(val));
    while (/(\d+)(\d{3})/.test(val.toString())){
        val = val.toString().replace(/(\d+)(\d{3})/, '$1'+','+'$2');
    }

    return '$ ' + val;

}

alert(formatNumber(1234567.89));

Fiddle:

http://jsfiddle.net/dybg5ye1/2/

Edit: forgot the dollar sign :)

foxygen
  • 1,368
  • 1
  • 11
  • 22
  • Thanks foxygen. What is the purpose of the while statement? – user1032531 Nov 02 '14 at 13:09
  • It allows us to iterate through the string, looking for at least one digit followed by 3 numbers, and if found, a comma is inserted and the value is updated. Once this condition is no longer met - the loop exits and the formatted value is returned – foxygen Nov 02 '14 at 13:19