Java的算术精度更高 [英] Java more precision in arithmetic
问题描述
我正在用Java构建一个Web应用程序,该应用程序可以进行数学运算并向用户显示步骤.当使用小数进行基本算术运算时,我经常会在准确的输出中感到混乱.
这是我的问题:
double a = 0.15;
double b = 0.01;
System.out.println(a - b);
// outputs 0.13999999999999999
float a = 0.15;
float b = 0.01;
System.out.println(a - b);
// outputs 0.14
float a = 0.16f;
float b = 0.01f;
System.out.println(a - b);
// outputs 0.14999999
double a = 0.16;
double b = 0.01;
System.out.println(a - b);
// outputs 0.15
对于complete
的准确性都不可靠.是否有一个更精确的数字类?或者我应该将这些值四舍五入吗?
您可以使用 请确保使用String参数或 而不是像这样的double参数: 因为如果您传递双精度数,那么您还将双精度数的不准确性传递到新的BigDecimal实例中.如果您传递一个String,BigDecimal将会知道™并且做正确的事情™. I am building a web app in Java that does math and shows steps to the user. When doing basic arithmetic with decimals I often get the messy in accurate outputs. Here is my problem: Neither is reliable for You can use BigDecimal for this. It's ugly, but it works: Be sure to construct them either with a String parameter, or with the And not with a double parameter, like this: Because if you pass in a double, you will also pass in double's inaccuracy into the new BigDecimal instance. If you pass in a String, BigDecimal will know™ and do the right thing™. 这篇关于Java的算术精度更高的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!valueOf
方法构造它们,如下所示:BigDecimal x = new BigDecimal("0.15"); // This is ok
BigDecimal x = BigDecimal.valueOf(0.15); // This is also ok
BigDecimal x = new BigDecimal(0.15); // DON'T DO THIS
double a = 0.15;
double b = 0.01;
System.out.println(a - b);
// outputs 0.13999999999999999
float a = 0.15;
float b = 0.01;
System.out.println(a - b);
// outputs 0.14
float a = 0.16f;
float b = 0.01f;
System.out.println(a - b);
// outputs 0.14999999
double a = 0.16;
double b = 0.01;
System.out.println(a - b);
// outputs 0.15
complete
accuracy. Is there a numeric class that is more precise or should I just round the values off?BigDecimal a = new BigDecimal("0.15");
BigDecimal b = new BigDecimal("0.01");
System.out.println(a.subtract(b));
valueOf
method, like this:BigDecimal x = new BigDecimal("0.15"); // This is ok
BigDecimal x = BigDecimal.valueOf(0.15); // This is also ok
BigDecimal x = new BigDecimal(0.15); // DON'T DO THIS