简体   繁体   中英

Creating a decimal number with no decimal separator

I am trying to receive an int, which is always a number with 2 decimals. Ex:

  • 1000 is 10,00 (my decimal separator is comma).
  • 100 is 1,00
  • 0 is 0,00
  • 100099 is 1.000,99

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM