hossein hossein - 7 months ago 10
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

String
values.

Basically, I want these results:

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


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


and ...

Answer

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.

Comments