Reputation: 219
I am trying to receive an int, which is always a number with 2 decimals. Ex:
So I'm trying to avoid using String operators and use the DecimalFormat with the pattern 0,00 and German locale.
But when I get 10004, the output that I obtain is 1.00.04
This is my code:
public static String formatDecimal(double number) {
//String pattern = "#,00";
String pattern = "0,00";
DecimalFormat fN = (DecimalFormat) NumberFormat.getNumberInstance(Locale.GERMAN);
fN.applyPattern(pattern);
return fN.format(number)
}
Upvotes: 1
Views: 2112
Reputation: 5578
Why would you use your own pattern? Java default implementation has pretty good patterns in most of locales. At least by looking Oracle's docs it looks that it should do what you need to:
Locale Formatted Numbers
German (Germany) 123.456,789
German (Switzerland) 123'456.789
English (United States) 123,456.789
So what you have to do ( besides dividing a number by 100 ) is set minimum fraction digits to "2":
public static String formatDecimal(double number) {
NumberFormat german = NumberFormat.getNumberInstance(Locale.GERMAN);
german.setMinimumFractionDigits(2);
return german.format(number / 100);
}
Edited: prints numbers as expected:
0,00
0,01
0,02
0,09
0,10
0,11
0,99
1,00
1,01
9,99
10,00
10,01
99,99
100,00
100,01
999,99
1.000,00
1.000,01
9.999,99
10.000,00
10.000,01
99.999,99
100.000,00
100.000,01
999.999,99
1.000.000,00
1.000.000,01
Upvotes: 2
Reputation: 53819
Try:
public static String formatDecimal(double number) {
DecimalFormatSymbols dfs = DecimalFormatSymbols.getInstance(Locale.GERMANY);
dfs.setGroupingSeparator('.');
return new DecimalFormat("0,00", dfs).format(number / 100);
}
formatDecimal(1000); // 10,00
formatDecimal(100); // 1,00
formatDecimal(0); // 0,00
formatDecimal(100099); // 1.000,99
Upvotes: 2