Java中的计算问题 [英] Calculation problem in Java

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

问题描述

我在Java中执行计算有点困难。这是我要做的 -



((0.053800 *(500000/1000))+ 4)* 0.85



在我的java应用程序中,它返回26.264999999999997,如果你舍入2位小数,就变成26.26。



但在MS Excel中,相同的公式返回26.265000 ..因此舍入结果为26.27。



如果我的Java应用程序返回不正确的值,什么

解决方案

以下是一个更好的近似,在这种情况下导致相同的值:

  import java.math.BigDecimal; 
import java.math.MathContext;

public class Test {
public static void main(String [] args){
// double d =((0.053800 *(500000/1000))+ 4)* 0.85;
BigDecimal d =((new BigDecimal(0.053800).multiply(new BigDecimal(500000).divide(new BigDecimal(1000))))add(new BigDecimal(4)))乘法(new BigDecimal ));
System.out.println(d.round(MathContext.DECIMAL32));
}
}


I'm having slight difficulty in performing a calculation in Java. Here is what I'm trying to do -

((0.053800 * (500000/1000)) + 4) * 0.85

In my java application, it returns 26.264999999999997, which if you round up to 2 decimal places, becomes 26.26.

But in MS Excel, the same formula returns 26.265000.. and therefore the rounded result is 26.27.

If my Java application is returning incorrect value, what can I do to correct it?

解决方案

The following is a much better approximation, which results in the same value in this case:

import java.math.BigDecimal;
import java.math.MathContext;

public class Test {
    public static void main(String[] args) {
        //double d = ((0.053800 * (500000/1000)) + 4) * 0.85;
        BigDecimal d = ((new BigDecimal(0.053800).multiply(new BigDecimal(500000).divide(new BigDecimal(1000)))).add(new BigDecimal(4))).multiply(new BigDecimal(0.85));
        System.out.println(d.round(MathContext.DECIMAL32));
    }
}

这篇关于Java中的计算问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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