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
Joined: Oct 14, 2001
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
Joined: Jan 30, 2000
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
Joined: Aug 08, 2003
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.