javalocalenumber-formatting

Java - NumberValue to String without Currency sign


I am trying to format a NumberValue as a String in the current locale format.

For example, for Locale.Germany these would be the results I am trying to get:

1   -> 1,00
1.1 -> 1,10
0.1 -> 0,10

What I have tried:

String test1 = NumberFormat.getInstance().format(1.1);
// -> 1,1
String test2 = NumberFormat.getCurrencyInstance().format(1.1);
// -> 1,10 €

How could I get the same format as the second example, without the currency symbol? Or alternativly, how could I make sure the result from the first example always has the amount of decimals needed for the current locale?

Edit: Since there are some currencies that have 0,2 or 3 decimals, I don't think setting the decimals to a fixed amount will have the correct results.

Also, some currencies have their symbol in the front, and some in the back, so cutting off the last characters will probably not work either.

http://apps.cybersource.com/library/documentation/sbc/quickref/currencies.pdf


Solution

  • java.util.Currency provides the necessary information. A reasonable approach to print currency values without the currency sign in pure Java code is to get a general-purpose NumberFormat instance and configure it to use the number of digits defined by the appropriate Currency object:

    NumberFormat numberFormat = NumberFormat.getInstance(myLocale);
    Currency currency = Currency.getInstance(myLocale);
    numberFormat.setMinimumFractionDigits(currency.getDefaultFractionDigits());
    

    If you need a specific currency as opposed to the default currency of the locale you use, use the String override of Currency.getInstance() instead and provide the appropriate currency code.