0

There is a random number (not necessarily positive or integer), say, -14383040.327843. I want to turn it into "(14,383,040)". So to spell it:

  • negative number has to be in brackets
  • fraction part should be stripped off without rounding
  • every N decimal places (3 by default) from right to left there has to be a separator (, by default)
  • no leading zeros

What is the fastest (across major browsers) way to get such string?

2
  • @epascarello value < 0 ? '(' + String(value.toFixed(0)).split('').reverse().chunk(3).map(function(chunk) { return chunk.reverse().join(''); }).join(',') + ')' : String(value.toFixed(0)).split('').reverse().chunk(3).map(function(chunk) { return chunk.reverse().join(''); }).join(',') Commented Oct 23, 2014 at 19:10
  • Probably not fast, just tried it out "-231423421342134.327843".split(".")[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",").replace(/^-(.+)/,"($1)"); Commented Oct 23, 2014 at 19:34

2 Answers 2

1
(Math.round(-14383040.327843)).toLocaleString();


/*  returned value: (String)
-14,383,040
*/

This value is returned in IE8 and IE10, Firefox 33,Opera 25 and Chrome 38.

To replace the minus-hyphen with parens-

(Math.round(-14383040.327843)).toLocaleString().replace(/\-(.+)/,'($1)');
Sign up to request clarification or add additional context in comments.

Comments

0

Try this.

x=-14383040.327843;
xf=Math.abs(x|0).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
xp=(x>0)?xf:"("+xf+")";

x is your variable, xf is formatted, and xp is for printing.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.