gpt4 book ai didi

java MonetaryConversions 为高位货币抛出 ArithmeticException

转载 作者:行者123 更新时间:2023-12-05 07:16:38 25 4
gpt4 key购买 nike

我想使用标准的 java MonetaryConversions 来转换货币。

乍一看它工作得很好而且简单:

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

但是,当我使用具有高面值的货币(如日元或墨西哥比索)时,我发现它会抛出 ArithmeticExceptions

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

抛出以下异常

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)

检查 FastMoney 的代码,我发现异常是硬编码的,我找不到任何可以减少的地方,例如规模。

但是有了这个,java 提供的开箱即用的转换就毫无用处,因为我无法转换很多货币。我无法想象没有人有这个问题。但是我用谷歌找不到任何东西。

最佳答案

作为dementis mentions in a comment:

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.

这对我有用。

关于java MonetaryConversions 为高位货币抛出 ArithmeticException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59181879/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com