为什么Java在浮点计算后会显示额外的值? [英] Why does Java shows extra values after float calculation?

查看:60
本文介绍了为什么Java在浮点计算后会显示额外的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一段非常简单的代码,我认为从用户的角度给出了错误的结果。

I have a very simple piece of code below which I think gives the wrong result from a user's perspective.

package com.test.sample;
public class Test {

    public static void main(String[] args) {
        float c,d;

        c = (float) 12.47;
        d = (float) 12.44;
        d = c - d;

        System.out.println("Hello the calculated value of a=" + d);
    }

}

输出为
你好a的计算值= 0.030000687

但是我要 a = 0.030000000 这是完美的价值。

But I want a=0.030000000 which is the perfect value.

推荐答案

浮点运算,开发人员应该知道的。

Floating point arithmetic, what developers should know.

JVM实现了 IEEE-754 1985浮点标准它有准确性问题(因为浮点数不能精确地代表所有真实的数字)。

The JVM implements the IEEE-754 1985 floating point standard and it has its accuracy problem (since floating point numbers cannot precisely represent all real numbers).

如果您寻求准确性,请改用 java.math.BigDecimal 对象。

If you seek accuracy, use java.math.BigDecimal object instead.

更新:这是我举例并使用的方式BigDecimal 来实现预期的结果:

Update: This is how I took your example and used BigDecimal to achieve your expected result:

import java.math.BigDecimal;

/**
 * @author The Elite Gentleman
 *
 */
public class BigDecimalTest {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        BigDecimal a = new BigDecimal(Float.toString(12.47f));
        BigDecimal b = new BigDecimal(Float.toString(12.44f));
        BigDecimal c = a.subtract(b);
        System.out.println(c);
    }
}

这篇关于为什么Java在浮点计算后会显示额外的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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