2016-04-21 103 views
-1

我知道如何設置數千個分隔符的數字,但我需要以String值的數學表達式顯示具有千位分隔符的數字。從java中的字符串值的數學表達式中格式化數字

基本上,我想這些結果:

"123456 + 36514"成爲"123,456 + 36,514"

"12345678 + 36542 * 69541/987654"成爲"12,345,678 + 36,542 * 69,541/987,654"

和...

+0

@aribeiro我認爲,正則表達式可以幫助我,但我不明白正則表達式。 – hossein

回答

1

你想要的後面是一個數字後面插入逗號確切數量的3位塊,所以:

(?<=\d)   Positive lookbehind: Match a digit 
(?=    Positive lookahead: 
    (?:\d{3})+  One or more sequences of 3 digits 
    \b    Word-boundary, i.e. end of digit sequence 
) 

,將符合你想要逗號空的空間,所以做了replaceAll()

str = str.replaceAll("(?<=\\d)(?=(?:\\d{3})+\\b)", ","); 

regex101 for demo

0

我可以爲您提供的算法而給出代碼:

Loop: String of repression one character at a time 
{ 
    If the current char is 0 to 9 append to tempNumber string 
    else 
    { 
     //by the time you reach this line the number is in the tempNumber string 

     Format the number stored in tempNumber // java.text.NumberFormat 
     append the formatted number in targetExpression string 
     append the current char to the targetExpression string 
} 

}