I know how to use comma in printf
as grouping separator to print value in format like
1,000,000.00
to print it that way I'm using command
System.out.printf ("%,.2f", value);
but how to use space as grouping separator to format value like
1 000 000.00
I tried to find solution but solutions with using DecimalFormat
look at now to complicate for me (beginner level).
Is there as easy way as in example with comma to do it?
Fast answer:
String result = String.format("%,.2f", value).replace(".", " ");
System.out.println(result);
(assuming you are using Java 1.5 or above).
Using DecimalFormat
:
DecimalFormat formatter = (DecimalFormat) NumberFormat.getInstance(Locale.getDefault());
DecimalFormatSymbols symbols = formatter.getDecimalFormatSymbols();
String.format(symbols.getGroupingSeparator(), ' ')
or even better:
symbols.setGroupingSeparator(' ');
f = new DecimalFormat("###,###.00", symbols);
System.out.println(f.format(value));
Printf doesnt handle this. Use println insted. Example from oracle:
DecimalFormatSymbols unusualSymbols = new DecimalFormatSymbols(currentLocale);
unusualSymbols.setDecimalSeparator('|');
unusualSymbols.setGroupingSeparator('^');
String strange = "#,##0.###";
DecimalFormat weirdFormatter = new DecimalFormat(strange, unusualSymbols);
weirdFormatter.setGroupingSize(4);
String bizarre = weirdFormatter.format(12345.678);
System.out.println(bizarre);
out : 1^2345|678
To convert Float to String:
println uses FloatingDecimal
printf uses FormattedFloatingDecimal
But I haven't time to look deeper why these classes are different. Enjoy reading :)
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