How Java’s Floating Point Hurts Everyone Everywhere

Consider the following Simple Code:

class SubTest{
public static void main(String[] args){
double a = 10.00;
double b = 10.60;
double c = 10.50;

System.out.println(“b – a :” + (b-a));
System.out.println(“c – a :” + (c-a));

What could be the output??

b – a :0.5999999999999996
c – a :0.5

Well, we know in simple maths 10.60 – 10.00 = .60;

But, why is the computation adding a small signed error to the result!!!. The computer floating point unit works internally in base 2, binary ie., the Representation of repeater fraction 1/3 = 0.33333 in base 10. Such fractions cannot be precisely represented in base10. The same fundamental mathematical cause is at work.

To avoid such errors, we can look at using BigDecimal:

import java.math.*;

public class SubTest1{
public static void main(String args[]){
BigDecimal num1 = new BigDecimal(“10.60”);
BigDecimal num2 = new BigDecimal(“10.00”);
BigDecimal result = num1.subtract(num2).setScale(2, BigDecimal.ROUND_HALF_UP);
System.out.println(“num1 – num2 :” + result);

And, the result:

num1 – num2 :0.60


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s