首页 > 解决方案 > 是否有任何 API 可以在 java 中格式化货币值?

问题描述

我有双倍的货币代码和价值。需要对货币进行格式化。我尝试使用 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.

标签: javaformatcurrencyeuro

解决方案


除非您真的需要手动执行此操作,否则我宁愿使用 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。文档


推荐阅读