问题描述:

I'm trying to format a double variable to a price string (example: €59,00) using NumberFormat

Here is the method I written:

private String formatValue (double price){

NumberFormat f = NumberFormat.getCurrencyInstance(Locale.ITALIAN);

String value = f.format(new BigDecimal(price));

return value;

}

then, I write the returned value in a pdf field using iText library.

form.setField("value", formatValue(price));

Now, when I open the generated pdf in a browser's pdf viewer (like chrome or firefox), the field looks like:

€59,00

but when I open it in adobe reader, or I try to physically print, it appears like

¤59,00.

If I open the variable value in debug, I see the string formatted as ¤59,00.

What I'm doing wrong?

I solved using DecimalFormat instead NumberFormat, and passing the € symbol in utf-8 encode (an input by mwhs [thanks])

private String formatValue (double price){

DecimalFormat formatter = new DecimalFormat("\u20ac0.00");

String value = formatter.format(price);

return value;

}

网友答案:

You may be using separate encoding. Browsers may be using UTF-8, Whereas adobe reader may be using ANSI or another localization of UTF. (Note these are not necessarily the encoding they use, just an example) so check your preferences, and try again.

网友答案:

You can use the actual UTF-8 Euro symbol which makes the code more readable.

  private static final DecimalFormat EURO_FORMAT = new DecimalFormat("€0.00");
  private String formatValue (double price){
    return EURO_FORMAT.format(price);
  }

But the java.util.NumberFormat is a better choice since you can use the Locale for the correct number format. In France, Germany and the Netherlands the comma is used instead of the decimal point before the cents. But the format for thousands is different. See below for an example:

public class NumberFormatLocaleExample {

  public static void main(final String[] args) {
    double price = 1249.69;
    System.out.println(formatValueGermany(price));
    System.out.println(formatValueFrance(price));
  }

  private static final NumberFormat EURO_FORMAT_GER = NumberFormat.getCurrencyInstance(Locale.GERMAN);
  private static String formatValueGermany(double price){
    return String.format("€%s", EURO_FORMAT_GER.format(price));
  }

  private static final NumberFormat EURO_FORMAT_FRANCE = NumberFormat.getCurrencyInstance(Locale.FRENCH);

  private static String formatValueFrance(double price){
    return String.format("€%s", EURO_FORMAT_FRANCE.format(price));
  }
}
相关阅读:
Top