0

我有双倍的货币代码和价值。需要对货币进行格式化。我尝试使用 NumberFormat 和 Locale,但在这种情况下,例如 EURO 具有与国家/地区相关的不同区域设置。我怎样才能做到这一点?欧元有什么通用格式吗?

       format.setCurrency(Currency.getInstance("EUR"));
       format.setMaximumFractionDigits(2);
       
       System.out.println(format.format(dbl));

Locale[] locales = NumberFormat.getAvailableLocales();

       for(Locale lo : locales){
           NumberFormat format = NumberFormat.getCurrencyInstance(lo);
           if(NumberFormat.getCurrencyInstance(lo).getCurrency().getCurrencyCode().equals("EUR")){
          
               System.out.println(    NumberFormat.getCurrencyInstance(lo).getCurrency().getCurrencyCode()+"-"+lo.getDisplayCountry() +"-"+NumberFormat.getCurrencyInstance(lo).getCurrency().getSymbol() +format.format(dbl));  

           }
       }```

Sorry previous question was closed.
4

3 回答 3

2

除非您真的需要手动执行此操作,否则我宁愿使用 java money

<dependency>
  <groupId>org.javamoney</groupId>
  <artifactId>moneta</artifactId>
  <version>1.4.1</version>
  <type>pom</type>
</dependency>

从未使用过它,但听起来它可以解决您的问题,有关更多信息,请查看文档https://github.com/JavaMoney/jsr354-ri/blob/master/moneta-core/src/main/asciidoc/userguide。文档

于 2021-08-11T09:10:30.247 回答
1

无需导入您需要学习和增加应用程序大小的外部 java 库。可以使用DecimalFormat带有两个参数的 using 构造函数,第一个是模式,第二个是要使用的符号:

使用给定的模式和符号创建一个 DecimalFormat。当您需要完全自定义格式的行为时,请使用此构造函数。

您可以在此处找到官方指南的详细信息

这是一个工作示例:

DecimalFormatSymbols symbols = new DecimalFormatSymbols();
symbols.setDecimalSeparator('.');
symbols.setGroupingSeparator(',');
symbols.setCurrency(Currency.getInstance("EUR"));
DecimalFormat df = new DecimalFormat("¤###,###.00", symbols);
System.out.println(df.format(5000.4));  // Will print €5.000,40    

下面是前面示例中使用的模式 ¤###,###.00 的描述

¤       is the currency symbol (in our case will be replaced by the EUR symbol)
###,### is the integer part of the number. Digits are grouped in group of 3 
.00     is the decimal part of the number. If less than 2 decimal numbers are presented zeroes are 
        added to the string so to have exactly 2 decimal numbers 

此示例不关心语言环境,因为格式化数字中使用的所有符号都被显式替换。

于 2021-08-11T09:08:04.533 回答
0
于 2021-08-11T09:42:27.047 回答