Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split digits with spaces by groups of 3 in java

Is there any way to split a double number in java so that all groups of 3 digits are splitted with a space and only 2 digits after a comma are appeared? It's easy to separate them with a comma:

DecimalFormat df = new DecimalFormat("###,###.00");
df.format(number);

So that 235235.234 turns into 234,234.23

What I need is 234 234.23

How can I do that?

like image 515
Sergey Avatar asked Aug 14 '12 07:08

Sergey


People also ask

How to separate digits in a number in Java?

You can convert a number into String and then you can use toCharArray() or split() method to separate the number into digits. String number = String. valueOf(someInt); char[] digits1 = number.

How do you split a string with spaces?

To split a string with space as delimiter in Java, call split() method on the string object, with space " " passed as argument to the split() method. The method returns a String Array with the splits as elements in the array.


1 Answers

I believe the comma in your format string isn't really a comma - it's just the grouping symbol in the DecimalFormatSymbols you're using.

Try this:

// TODO: Consider specifying a locale
DecimalFormatSymbols symbols = new DecimalFormatSymbols();
symbols.setGroupingSeparator(' ');
DecimalFormat df = new DecimalFormat("###,###.00", symbols);

Or as an alternative for the last line:

DecimalFormat df = new DecimalFormat();
df.setDecimalFormatSymbols(symbols);
df.setGroupingSize(3);
df.setMaximumFractionDigits(2);
like image 175
Jon Skeet Avatar answered Sep 24 '22 02:09

Jon Skeet