Search code examples
javacurrencynumber-formatting

java: get different parts of NumberFormat.getCurrencyInstance() result


In Java, with NumberFormat.getCurrencyInstance(), I can get a formatted string representing a price. e.g.

NumberFormat nf = NumberFormat.getCurrencyInstance(Locale.GERMANY);
System.out.println(nf.format(20.10)); // "20,10 €"

Is there an easy way to get the different part of this formatted string? i.e. something like

integerPart -> 20
decimalPart -> 10
currencySymbol -> €
decimalSeparator -> ,

Thanks!


Solution

  • You're really asking for two separate things:

    1. integerPart and decimalPart belong to the input value. They can be calculated with some simple math:

      double input = 20.10;
      int integerPart = (int)input; // 20
      int decimalPart = (int)((input - integerPart) * 100); // 10
      
    2. currencySymbol and decimalSeparator relate to the output value. They can be retrieved using the DecimalFormatSymbols class:

      DecimalFormatSymbols symbols = DecimalFormatSymbols.getInstance(Locale.GERMANY);
      String currencySymbol = symbols.getCurrencySymbol(); // €
      char decimalSeparator = symbols.getDecimalSeparator(); // ,