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?
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.
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With