Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert commas into number string

Hey there, I'm trying to perform a backwards regular expression search on a string to divide it into groups of 3 digits. As far as i can see from the AS3 documentation, searching backwards is not possible in the reg ex engine.

The point of this exercise is to insert triplet commas into a number like so:

10000000 => 10,000,000 

I'm thinking of doing it like so:

string.replace(/(\d{3})/g, ",$1") 

But this is not correct due to the search not happening from the back and the replace $1 will only work for the first match.

I'm getting the feeling I would be better off performing this task using a loop.

UPDATE:

Due to AS3 not supporting lookahead this is how I have solved it.

public static function formatNumber(number:Number):String {     var numString:String = number.toString()     var result:String = ''      while (numString.length > 3)     {         var chunk:String = numString.substr(-3)         numString = numString.substr(0, numString.length - 3)         result = ',' + chunk + result     }      if (numString.length > 0)     {         result = numString + result     }      return result } 
like image 205
BefittingTheorem Avatar asked Apr 06 '09 12:04

BefittingTheorem


People also ask

How do you use commas in a string?

To split a string with comma, use the split() method in Java. str. split("[,]", 0);

How do you add commas in numbers in Python?

In Python, to format a number with commas we will use “{:,}” along with the format() function and it will add a comma to every thousand places starting from left. After writing the above code (python format number with commas), Ones you will print “numbers” then the output will appear as a “ 5,000,000”.


1 Answers

If your language supports postive lookahead assertions, then I think the following regex will work:

(\d)(?=(\d{3})+$) 

Demonstrated in Java:

import static org.junit.Assert.assertEquals;  import org.junit.Test;  public class CommifyTest {      @Test     public void testCommify() {         String num0 = "1";         String num1 = "123456";         String num2 = "1234567";         String num3 = "12345678";         String num4 = "123456789";          String regex = "(\\d)(?=(\\d{3})+$)";          assertEquals("1", num0.replaceAll(regex, "$1,"));         assertEquals("123,456", num1.replaceAll(regex, "$1,"));         assertEquals("1,234,567", num2.replaceAll(regex, "$1,"));         assertEquals("12,345,678", num3.replaceAll(regex, "$1,"));         assertEquals("123,456,789", num4.replaceAll(regex, "$1,"));         }     } 
like image 104
toolkit Avatar answered Oct 12 '22 01:10

toolkit