programming forums Java Java JSRs Mobile Certification Databases Caching Books Engineering OS Languages Paradigms IDEs Build Tools Frameworks Products This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
Sheriffs:
Saloon Keepers:
Bartenders:

# Subtraction of double values

Aarti Pednekar
Greenhorn
Posts: 8
I am doing the following subtraction using 2 double values
class temp
{
public static void main(String[] args)
{
double d = 200.123;
double f = 100.123;
double t = d - f;
System.out.println("t " + t);
}
}

Ans:
t 99.99999999999999

I get the result as above instead of 100. Can anyone tell me why this is happening? Also, similar results are observed if I give 200.1234 - 100.1234 and 200.4567 - 100.4567. Under all other cases the subtraction seems to be working fine
Under all other conditions the subtraction of doubles works fine

marc weber
Sheriff
Posts: 11343
A classic reference, "Some things you should know about floating point arithmetic."

Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24217
38
Floating-point numbers are an approximation to the mathematical idea of real numbers. Since a floating-point number has only a fixed number of bits, it has only a fixed accuracy, and there are many values that can't be represented exactly. Java's floating point number (and those of virtually all other modern computing environments) are represented in a binary (base 2) system. Numbers that come out "even" in decimal notation (like 100.123) may actually not come out exactly in binary. The reverse is often true, too: numbers for which you'd have to use an infinitely repeating decimal representation come out to a finite number of exact digits in binary.

So anyway -- the thing to remember is that doubles (and floats) are only approximations to mathematically pure real numbers, and you'll often get results like this. If you want to print a double with a specific number of decimal places, then you always need to use, e.g., the java.text.DecimalFormat class to format it to your liking.

Aarti Pednekar
Greenhorn
Posts: 8
Are there other cases apart from these 3 cases where the subtraction gives faulty results? I tested under lot of other conditions and the subt of 2 doubles gives the correct results. I am specifically interested in subtracting numbers which have a max of 4 digits after the decimal.

Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24217
38
These are not faulty results. All floating point numbers are only approximations. Read the article linked above!

Jesper de Jong
Java Cowboy
Sheriff
Posts: 16060
88
If you want to do arbitrary precision calculations, use java.math.BigDecimal instead of double.

By the way, this is not a Java-specific problem. It happens with any programming language that uses IEEE 754 floating point numbers.
[ December 09, 2005: Message edited by: Jesper de Jong ]

 It is sorta covered in the JavaRanch Style Guide.