hossein hossein - 2 years ago 57
Java Question

Formatting numbers in a mathematical expression from String values in java

I know how to set thousands separator for numbers but i need to display numbers with thousands separator in mathematical expression from


Basically, I want these results:

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

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

and ...

Answer Source

You want to insert comma after a digit that is followed by an exact number of 3-digit blocks, so:

(?<=\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

That will match the empty spaces where you want commas, so do a replaceAll():

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

See regex101 for demo.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download