Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Space as grouping separator in printf

Tags:

java

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?

like image 442
blekione Avatar asked Nov 09 '12 10:11

blekione


2 Answers

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));
like image 152
jalopaba Avatar answered Nov 08 '22 03:11

jalopaba


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 :)

like image 23
KrHubert Avatar answered Nov 08 '22 04:11

KrHubert