This is the first time I noticed this but in my program I have to make an exact copy of a BigDecimal object, basically clone it. I perform the following code: BigDecimal original = new BigDecimal("0.02"); BigDecimal copy = new BigDecimal(original.doubleValue()); System.out.println("Original: " + original); System.out.println("Copy: " + copy); and the following is the output: Original: 0.02 Copy: 0.0200000000000000004163336342344337026588618755340576171875 The double gets extra numbers to the right of the decimal. Obviously this is not good. Is this a bug and is there a simple way to prevent this? Any suggestions Thanks
David Peterson
author
Ranch Hand
Joined: Oct 14, 2001
Posts: 154
posted
0
Simple way to prevent it? BigDecimal copy = new BigDecimal(original.toString()); But actually there is no point in doing this, since the value of a BigDecimal is immutable, you can simply use the original BigDecimal, or if you want to give it a new name for some reason... copy = original; David
Jim Yingst
Wanderer
Sheriff
Joined: Jan 30, 2000
Posts: 18670
posted
0
I agree with David's answer. In addition: Is this a bug Fundamentally, it's not possible for a double to represent all the possibile precise values that a BigDecimal cna represent. If it were, we wouldn't need BigDecimal at all. So whenever you invoke the doubleValue() method of BigDecimal, you have to realize you're asking for what may be an approximation to the original value.
"I'm not back." - Bill Harding, Twister
Joshua Doerring
Greenhorn
Joined: Aug 08, 2003
Posts: 19
posted
0
The better solution is not to copy it at all. I was just having this problem in a clone method of one of our classes and it just didn't occur to me at the time when you see everything else being copied. Thanks for the help.
I agree. Here's the link: http://ej-technologies/jprofiler - if it wasn't for jprofiler, we would need to
run our stuff on 16 servers instead of 3.