如何从 java 中的示例价格中提取货币和数字属性

问题描述 投票:0回答:1

我正在检索不同货币的产品价格的不同值 例如:

$ 1213.22
1213\.22 $
R$ 1213,22

我想将这些值存储在格式化的 Java 对象中,以便我可以提取:

  1. 货币符号
  2. 整价和分价之间的分隔符
  3. 整价
  4. 零星价格

除了使用正则表达式之外,还有其他实用程序可以做到这一点吗?

探索的解决方案

  1. 我找不到一种方法来对以下解决方案进行逆向工程,以便让 NumberFormat 接受我检索到的值

    java.util.Currency usd = java.util.Currency.getInstance("USD");
    java.text.NumberFormat format = java.text.NumberFormat.getCurrencyInstance(Locale.US);
    format.setCurrency(usd);
    
  2. 和1号一样的问题

    StringBuilder builder=new StringBuilder();
    Formatter f=new Formatter(builder);
    f.format(Locale.FRANCE,"%.5f", -1325.789);
    
java format locale currency price
1个回答
0
投票
  1. 你可以像这样创建一个类,并有方法返回你想要的值。

     public class Price {
     private String currency;
     private String separator;
     private int wholePrice;
     private int fractionalPrice;
    
     public Price(String currency, String separator, int wholePrice, int fractionalPrice) {
         this.currency = currency;
         this.separator = separator;
         this.wholePrice = wholePrice;
         this.fractionalPrice = fractionalPrice;
     }
    
     public String getCurrency() {
         return currency;
     }
    
     public String getSeparator() {
         return separator;
     }
    
     public int getWholePrice() {
         return wholePrice;
     }
    
     public int getFractionalPrice() {
         return fractionalPrice;
     }
     }
    
  2. 然后使用此代码更新您的类,这样您就可以根据需要访问任何属性。

    Pattern pattern = Pattern.compile("^(\\p{Sc})\\s*(\\d+)([,.])(\\d+)$");
    Matcher matcher = pattern.matcher(priceStr);
    
    if (matcher.find()) {
        String currency = matcher.group(1);
        String separator = matcher.group(3);
        int wholePrice = Integer.parseInt(matcher.group(2));
        int fractionalPrice = Integer.parseInt(matcher.group(4));
        Price price = new Price(currency, separator, wholePrice, fractionalPrice);
        System.out.println("Currency: " + price.getCurrency());
        System.out.println("Separator: " + price.getSeparator());
        System.out.println("Whole price: " + price.getWholePrice());
        System.out.println("Fractional price: " + price.getFractionalPrice());
    } else {
        System.out.println("Invalid price format");
    }
    
    
    

希望这有帮助

© www.soinside.com 2019 - 2024. All rights reserved.