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

时间:2017-10-11 07:42:32

标签: java double currency

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

Double cents = new Double(dollar*100);
int amount = cents.intValue();

这种方法有多准确?有没有更好的方法来做到这一点。

3 个答案:

答案 0 :(得分:4)

由于您已将值设置为double,因此您已经引入了一些不精确性:您存储的数字可能与您要存储的值不完全相同。为了解决这个问题,我建议将它四舍五入到最近的分数。您可以使用Math.round执行此操作:

int cents = (int) Math.round(100*dollars);

答案 1 :(得分:0)

与大多数事物一样,“这取决于”。这取决于您的确切情况和您的程序正在解决的问题空间。你的设计案例的双打和浮动方法看起来很好。但是,在钱的情况下,许多人和图书馆只选择使用整数数学。这在名义上最小化了在高精度和高精度至关重要的情况下的舍入误差。评估自己和用例是否有效。

与此同时,将该思维过程应用于您的案例,您可能只使用分数并仅转换为演示文稿。或者,更好的是,将逻辑封装在Currency类和可能的USD类中:

int amountInCents = ....
int amountInDollars = round(amountInCents / 100.0);

注意使用显式小数来告诉编译器避免整数除法。因此,精明将在此代码中看到隐藏的浮点数学。

答案 2 :(得分:0)

这是对answer recommending rounding的支持。该程序将问题中的舍入和截断代码的结果与一系列值进行比较。它使用BigDecimal算法生成值,避免循环中的累积舍入误差。如果舍入和截断的结果不同,则打印数字。

import java.math.BigDecimal;

public class Test {
  public static void main(String[] args) {
    BigDecimal rawDollar = BigDecimal.ZERO;
    BigDecimal increment = new BigDecimal("0.01");
    for (int i = 0; i < 300; i++) {
      rawDollar = rawDollar.add(increment);
      double dollar = rawDollar.doubleValue();
      Double cents = new Double(dollar * 100);
      int amount = cents.intValue();
      int roundedAmount = (int) Math.round(dollar * 100);
      if (amount != roundedAmount) {
        System.out.println("dollar = " + dollar + " amount = " + amount
            + " rounded = " + roundedAmount);
      }
    }
  }
}

这是输出。在每个印刷案例中,舍入的数量是正确的,截断的数量比它应该小1美分。

dollar = 0.29 amount = 28 rounded = 29
dollar = 0.57 amount = 56 rounded = 57
dollar = 0.58 amount = 57 rounded = 58
dollar = 1.13 amount = 112 rounded = 113
dollar = 1.14 amount = 113 rounded = 114
dollar = 1.15 amount = 114 rounded = 115
dollar = 1.16 amount = 115 rounded = 116
dollar = 2.01 amount = 200 rounded = 201
dollar = 2.03 amount = 202 rounded = 203
dollar = 2.05 amount = 204 rounded = 205
dollar = 2.07 amount = 206 rounded = 207
dollar = 2.26 amount = 225 rounded = 226
dollar = 2.28 amount = 227 rounded = 228
dollar = 2.3 amount = 229 rounded = 230
dollar = 2.32 amount = 231 rounded = 232
dollar = 2.51 amount = 250 rounded = 251
dollar = 2.53 amount = 252 rounded = 253
dollar = 2.55 amount = 254 rounded = 255