使用Java将不同国家的货币转换为两倍 [英] Converting different countrys currency to double using 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.,]",""));
}
这需要金额的String
和Locale
.然后,它创建一个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屋!