java多种货币的相互转换,使用Java将不同国家的货币转换为两倍

I have once scenario where in i get the currencies as a String, for eg:

$199.00

R$ 399,00

£25.00

90,83 €

AED 449.00

How do i convert these currencies to double in java?

解决方案

Never use double for representing exact amounts

Well, of course you can do, but you need to really understand floating point arithmetic

Use a NumberFormat. Whilst it does handle some currencies, it's usually easier just to strip all the currency symbols. The NumberFormat will use Locale to work out the delimiters to use:

public static BigDecimal parse(final String amount, final Locale locale) throws ParseException {

final NumberFormat format = NumberFormat.getNumberInstance(locale);

if (format instanceof DecimalFormat) {

((DecimalFormat) format).setParseBigDecimal(true);

}

return (BigDecimal) format.parse(amount.replaceAll("[^\\d.,]",""));

}

This takes a String of the amount and the Locale. It then creates a BigDecimal parsing NumberFormat instance. It uses replaceAll and regex to strip all but digits, . and , from the number then parses it.

A quick demo against your examples:

public static void main(String[] args) throws ParseException {

final String dollarsA = "$199.00";

final String real = "R$ 399,00";

final String dollarsB = "£25.00";

final String tailingEuro = "90,83 €";

final String dollarsC = "$199.00";

final String dirham = "AED 449.00";

System.out.println(parse(dollarsA, Locale.US));

System.out.println(parse(real, Locale.FRANCE));

System.out.println(parse(dollarsB, Locale.US));

System.out.println(parse(tailingEuro, Locale.FRANCE));

System.out.println(parse(dollarsC, Locale.US));

System.out.println(parse(dirham, Locale.US));

}

Output:

199.00

399.00

25.00

90.83

199.00

449.00

I have simply used US where the decimal is . and FRANCE where the decimal is , but you could use the correct Locale for the currency if you wish.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值