146 percent Russian
146 percent Russian

Reputation: 2096

The easiest way to format string like 1 000 000

In my android program I display big numbers. To make them easy-reading I want to format these numbers not like 1000000 but like 1 000 000.

Which is the easiest way to format strings like this?

Upvotes: 3

Views: 841

Answers (3)

Maroun
Maroun

Reputation: 95948

Use NumberFormat with Locale#US to add ,s to the number:

String myNumber = NumberFormat.getNumberInstance(Locale.US).format(number);

And then replace every , with a space:

myNumber = myNumber.replace(",", " ");

Or, as @EvgeniyDorofeev suggested, use Locale#FRANCE and you won't have to replace anything :)


Please note the difference between replace and replaceAll. See String#replace that accepts a CharSequence and please try the code.

They both replace all characters, replaceAll accepts a regex, which I don't need in this case.

Upvotes: 5

Elliott Frisch
Elliott Frisch

Reputation: 201429

You can use String.format like so,

long num = 1000000;
System.out.println(String.format("%,d", num).replace(",", " "));

Output is

1 000 000

Upvotes: 2

Evgeniy Dorofeev
Evgeniy Dorofeev

Reputation: 135992

try this

String s = NumberFormat.getNumberInstance(Locale.FRANCE).format(1000000);

Upvotes: 8

Related Questions