Meaningless Drivel is fun!
The moose likes Beginning Java and the fly likes Bug cloning a BigDecimal Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Bug cloning a BigDecimal" Watch "Bug cloning a BigDecimal" New topic

Bug cloning a BigDecimal

Joshua Doerring

Joined: Aug 08, 2003
Posts: 19
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
David Peterson
Ranch Hand

Joined: Oct 14, 2001
Posts: 154
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;
Jim Yingst

Joined: Jan 30, 2000
Posts: 18671
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

Joined: Aug 08, 2003
Posts: 19
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:
subject: Bug cloning a BigDecimal
jQuery in Action, 3rd edition