Java的算术精度更高 [英] Java more precision in arithmetic

查看:70
本文介绍了Java的算术精度更高的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用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参数或valueOf方法构造它们,如下所示:

BigDecimal x = new BigDecimal("0.15");   // This is ok
BigDecimal x = BigDecimal.valueOf(0.15); // This is also ok

而不是像这样的double参数:

BigDecimal x = new BigDecimal(0.15); // DON'T DO THIS

因为如果您传递双精度数,那么您还将双精度数的不准确性传递到新的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:

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

Neither is reliable for complete accuracy. Is there a numeric class that is more precise or should I just round the values off?

解决方案

You can use BigDecimal for this. It's ugly, but it works:

BigDecimal a = new BigDecimal("0.15");
BigDecimal b = new BigDecimal("0.01");
System.out.println(a.subtract(b));

Be sure to construct them either with a String parameter, or with the valueOf method, like this:

BigDecimal x = new BigDecimal("0.15");   // This is ok
BigDecimal x = BigDecimal.valueOf(0.15); // This is also ok

And not with a double parameter, like this:

BigDecimal x = new BigDecimal(0.15); // DON'T DO 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆