使用Java将不同国家的货币转换为两倍 [英] Converting different countrys currency to double using java

查看:107
本文介绍了使用Java将不同国家的货币转换为两倍的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我曾经有一种情况,在这种情况下,我会以String的形式获取货币,例如:

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

$ 199.00

R $ 399,00

R$ 399,00

25.00英镑

90,83€

449.00迪拉姆

如何在Java中将这些货币转换为两倍?

How do i convert these currencies to double in java?

推荐答案

请勿使用double表示确切金额

Never use double for representing exact amounts

当然可以,但是您需要真正了解浮点运算

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

使用NumberFormat.尽管它确实可以处理一些货币,但通常只要剥离所有货币符号就更容易了. NumberFormat将使用Locale来确定要使用的分隔符:

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.,]",""));
}

这需要金额的StringLocale.然后,它创建一个BigDecimal解析NumberFormat实例.它使用replaceAll和正则表达式从数字中除去除数字之外的所有字符,然后将其解析.,.

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));
}

输出:

199.00
399.00
25.00
90.83
199.00
449.00

我只是使用了US,其中小数点是.,而FRANCE是小数点是,,但是如果您愿意,可以使用正确的Locale作为货币.

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.

这篇关于使用Java将不同国家的货币转换为两倍的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆