在Java中将美元转换为美分的最准确方法是什么

Geo*_*mas -2 java double currency

在Java中,将Double值的Dollar转换为cents的美分的最佳方法是什么。目前,我使用以下方法:

Double cents = new Double(dollar*100);
int amount = cents.intValue();
Run Code Online (Sandbox Code Playgroud)

这种方法有多精确?有没有更好的方法可以做到这一点。

khe*_*ood 5

由于您已将值加倍,因此您已经引入了一些不精确的含义:您存储的数字可能与您要存储的值不完全相同。为了解决这个问题,我建议将其四舍五入到最接近的一分。您可以使用Math.round

int cents = (int) Math.round(100*dollars);
Run Code Online (Sandbox Code Playgroud)

  • BigDecimal的想法也可以使用,但只能在强制使用MathContext的情况下获得整数精度和四舍五入。这是一个更直接的解决方案。 (2认同)