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

问题描述:

什么是将美元换算成双值的最好方法是将美分转换为Java中的整数值。目前我使用以下方法:在Java中将美元兑换为美分的最准确方法是什么

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

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

+0

'int amount =(int)(double * 100)'? – geisterfurz007

+3

你最好没有“双重”价值开始。 – khelwood

+0

@khelwood,我现在无法更改dayatypes –

既然你已经把你的价值放在了一倍,你已经引入了一些不准确:你存储的数字可能并不完全是你想存储的值。为了解决这个问题,我建议将它舍入到最接近的分数。您可以使用Math.round

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

BigDecimal想法也可以工作,但只能用强制MathContext才能获得整数精度和舍入到最近。这是一个更直接的解决方案。 –

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

同时,将思考过程应用于您的案例,您可能只需使用美分并仅为演示文稿进行转换。或者,更好的是,封装逻辑在货币类,或许美元类:

int amountInCents = .... 
int amountInDollars = round(amountInCents/100.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); 
     } 
    } 
    } 
} 

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

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