作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我想使用标准的 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/
我想使用标准的 java MonetaryConversions 来转换货币。 乍一看它工作得很好而且简单: @Test public void testConversion()
我是一名优秀的程序员,十分优秀!