Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add commas or spaces to group every three digits

I have a function to add commas to numbers:

function commafy( num ) {   num.toString().replace( /\B(?=(?:\d{3})+)$/g, "," ); } 

Unfortunately, it doesn't like decimals very well. Given the following usage examples, what is the best way to extend my function?

commafy( "123" )                 // "123" commafy( "1234" )                // "1234"                                  // Don't add commas until 5 integer digits commafy( "12345" )               // "12,345" commafy( "1234567" )             // "1,234,567" commafy( "12345.2" )             // "12,345.2" commafy( "12345.6789" )          // "12,345.6789"                                  // Again, nothing until 5 commafy( ".123456" )             // ".123 456"                                  // Group with spaces (no leading digit) commafy( "12345.6789012345678" ) // "12,345.678 901 234 567 8" 

Presumably the easiest way is to first split on the decimal point (if there is one). Where best to go from there?

like image 924
Sophie Alpert Avatar asked Jul 22 '11 01:07

Sophie Alpert


People also ask

Why is there a comma after 3 digits?

A comma is placed every third digit to the left of the decimal point and so is used in numbers with four or more digits. Continue to place a comma after every third digit. For example: $1,000,000 (one million dollars)

Is a group of digits separated by a comma or space?

When a number is written in standard form, each group of digits separated by a comma is called a period .


1 Answers

Just split into two parts with '.' and format them individually.

function commafy( num ) {     var str = num.toString().split('.');     if (str[0].length >= 5) {         str[0] = str[0].replace(/(\d)(?=(\d{3})+$)/g, '$1,');     }     if (str[1] && str[1].length >= 5) {         str[1] = str[1].replace(/(\d{3})/g, '$1 ');     }     return str.join('.'); } 
like image 112
Ghostoy Avatar answered Oct 13 '22 01:10

Ghostoy