Effective USD formatting in Javascript

Let's say I have a line: 33400298.57

I wrote a function (too long, too bloated, too custom to post here) that formats this:

33,400,298.57

Soft logic is the insertion of commas - to the left of the decimal point, every three places. Could there be a single line solution using regex for this? I am currently splitting, reversing, looping to insert, reverse and join again. Needless to say, this is not optimal.

I am looking for something like this:

Random color generator: '#' + Math.floor (Math.random () * 16777215) .toString (16);

Thank.

+3
source share
3 answers

:

s = "33400298.57";
s.replace(/(?!^)(\d\d\d)(?=(\d\d\d)*\.)/g, ',$1'); // 33,400,298.57
+2

jQuery JavaScript, jQuery. - :

http://code.google.com/p/jquery-formatcurrency/

JavaScript, . . .

0

Well, there is Number toLocaleString:

Number(12345.67).toLocaleString();

However, it is locale-specific, therefore warns emptor.

0
source

Source: https://habr.com/ru/post/1743798/


All Articles