Vins
Vins

Reputation: 4119

Why does Java shows extra values after float calculation?

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);
    }

}

The output is Hello the calculated value of a=0.030000687

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

Upvotes: 0

Views: 991

Answers (1)

Buhake Sindi
Buhake Sindi

Reputation: 89169

Floating point arithmetic, what developers should know.

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).

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


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);
    }
}

Upvotes: 6

Related Questions