hossein hossein - 6 months ago 3x
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 ...


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.