Win a copy of Functional Reactive Programming this week in the Other Languages forum!

# double

Soundar Sweet
Ranch Hand
Posts: 31

Remko Strating
Ranch Hand
Posts: 893
You can solve this problem by using the NumberFormat class in stead of the String class

The following code will give the right result

I don't know why the String.valueOf is not giving the right value.

Maybe someone else can tell us this.

I hope this helps

Keith Lynn
Ranch Hand
Posts: 2409
Some floating point numbers cannot be stored exactly.

Remko Strating
Ranch Hand
Posts: 893
Could you tell me when these are not stored exactly.

I had this week the same problem which i solved by using the NumberFormat class, but I couldn't explain the behavior.

Keith Lynn
Ranch Hand
Posts: 2409
Well the problem is that in order to be stored in a computer, a number has to be converted to binary.

However, there are decimal numbers which can't be converted to an exact binary number like whole numbers can.

For example, 1/10 cannot be converted exactly.

If you do a google search on it, I think there are sites that explain it.

fred rosenberger
lowercase baba
Bartender
Posts: 12196
35
heck, some DECIMAL fractions cannot be represented exactly in a finite space... 1/3 is NOT equal to 0.33333333333333, no matter how many "3"s you can store. 1/7 is NOT equal to 0.142857142857, but that's about the best your computer can do. since the computer has limited space, there will often be rounding.

Remko Strating
Ranch Hand
Posts: 893

I understand that numbers cannot be always exactly stored in computer memory. This causes that sometimes the ValueOf method of the String will return a strange value, because this method will return the exact double value in memory.

The solution for this is using the NumberFormat.

Jesper de Jong
Java Cowboy
Saloon Keeper
Posts: 15484
43
Originally posted by wilhelm tell:
The solution for this is using the NumberFormat.

Just using NumberFormat does not suddenly make the value stored in the double variable more precise. It just rounds the number before it's printed on screen, so that you see the value that you expect. But this does not necessarily always work correctly - if the extra precision isn't there, then NumberFormat cannot magically create the missing information.

If you really need arbitrary precision (for example because you are working with money, in which rounding errors are not acceptable), you should use class BigDecimal instead of double.

fred rosenberger
lowercase baba
Bartender
Posts: 12196
35
Actually, if you are working with money, the commonly used practice is to use some kind of Integer, and work in pennies (or the equivilent of the currency you are working with), then format that appropriatly for display.