Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Bug cloning a BigDecimal

 
Joshua Doerring
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 154
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Joshua Doerring
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic