java MonetaryConversions 抛出高位数货币的算术异常。

问题描述 投票:1回答:1

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

乍一看,它工作得很好,也很简单,但我发现,当我使用高面值的货币,如日本的日元或墨西哥的墨西哥币时,它会抛出算术异常。

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

但是我发现当我使用高面值的货币,比如日元或墨西哥比索时,会产生算术异常。

    @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提供的转换功能就很无用了,因为我不能转换很多货币。我不能想象没有人有这个问题。但我在谷歌上找不到任何东西。

java currency arithmeticexception java-money
1个回答
0
投票

作为 dementis在评论中提到。

你可以使用基于bigdecimal的Money类吗? FastMoney类是基于long的,你不应该依赖它来进行高精度的货币计算.

这对我来说是可行的。

© www.soinside.com 2019 - 2024. All rights reserved.