我正在检索不同货币的产品价格的不同值 例如:
$ 1213.22
1213\.22 $
R$ 1213,22
我想将这些值存储在格式化的 Java 对象中,以便我可以提取:
除了使用正则表达式之外,还有其他实用程序可以做到这一点吗?
探索的解决方案
我找不到一种方法来对以下解决方案进行逆向工程,以便让 NumberFormat 接受我检索到的值
java.util.Currency usd = java.util.Currency.getInstance("USD");
java.text.NumberFormat format = java.text.NumberFormat.getCurrencyInstance(Locale.US);
format.setCurrency(usd);
和1号一样的问题
StringBuilder builder=new StringBuilder();
Formatter f=new Formatter(builder);
f.format(Locale.FRANCE,"%.5f", -1325.789);
你可以像这样创建一个类,并有方法返回你想要的值。
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;
}
}
然后使用此代码更新您的类,这样您就可以根据需要访问任何属性。
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");
}
希望这有帮助