I’m am currently working on a program in java which requires adding a small constant value such as 0.00000000001 to a double variable, ex. location. However, when I run the code, debug it, and get to the place where I add 0.00000000001 to location, and check the value of location in debug mode after the addition takes place. It appears that location doesn’t have 0.00000000001 added to it. For example, location will equal 438.0 before the addition and 438.0 after the addition. Here is a example of what the simple code looks like
location += 0.00000000001
Any ideas? Thanks in advance.
Many double values are not exactly precise in Java due to the way it is stored. Exact precision only applies for certain values. This is because Java can only store a decimal value as a combination of many 2^n (s).
Eg:
1/4can be stored as2^-2, but1/3will be stored as2^-2 + 2^-3+ 2^-4 +2^-5..., so1/3is an example of a value that is not exactly preciseIf you want a precise value, use the
BigDecimalclass:http://docs.oracle.com/javase/7/docs/api/java/math/BigDecimal.html