简体   繁体   English

java MonetaryConversions 为高位货币抛出 ArithmeticException

[英]java MonetaryConversions throws ArithmeticException for high digit currencies

I'd like to use standard java MonetaryConversions to convert currencies.我想使用标准的 java MonetaryConversions 来转换货币。

At first glance it works very well and simple:乍一看,它工作得很好而且很简单:

    @Test
    public void testConversion()
    {
        FastMoney usd = FastMoney.of(1000, Monetary.getCurrency("USD"));
        usd.with(MonetaryConversions.getConversion("EUR"));
    }

However I find that is throws ArithmeticExceptions, when I use currencies that have high nominal values like japanese yen or Mexican Pesos但是,当我使用日元或墨西哥比索等具有高名义价值的货币时,我发现这会引发 ArithmeticExceptions

    @Test
    public void testArithmeticException()
    {
        FastMoney jpy = FastMoney.of(1000, Monetary.getCurrency("JPY"));
        jpy.with(MonetaryConversions.getConversion("EUR"));
    }

throws following exception抛出以下异常

java.lang.ArithmeticException: 0.0082769 can not be represented by this class, scale > 5

    at org.javamoney.moneta.FastMoney.getInternalNumber(FastMoney.java:197)
    at org.javamoney.moneta.FastMoney.multiply(FastMoney.java:388)
    at org.javamoney.moneta.FastMoney.multiply(FastMoney.java:84)
    at org.javamoney.moneta.spi.AbstractCurrencyConversion.apply(AbstractCurrencyConversion.java:118)
    at org.javamoney.moneta.FastMoney.with(FastMoney.java:594)
    at tech....GatewayTransactionConverterTest.testArithmeticException(GatewayTransactionConverterTest.java:207)

Checking the code of FastMoney I see that the exception is quite hardcoded and I cant find anything where I could reduce eg the scale.检查 FastMoney 的代码,我发现异常是硬编码的,我找不到任何可以减少的地方,例如规模。

But with this the conversion offered by java out of the box is quite useless as I cannot convert for really a lot of currencies.但是有了这个,java 提供的开箱即用转换是非常无用的,因为我无法转换为很多货币。 I cannot imagine that nobody has this issue.我无法想象没有人有这个问题。 But I can't find anything with google.但是我用谷歌找不到任何东西。

As dementis mentions in a comment:正如dementis 在评论中提到的:

Can you use the bigdecimal-based Money class?The FastMoney class is based on longs, which you shouldn't rely on for high precision currency calculations.您可以使用基于 bigdecimal 的 Money 类吗?FastMoney 类基于 longs,您不应该依赖它进行高精度货币计算。

this worked for me.这对我有用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM