Is the new BigDecimal from another bigDecimal.toString () always equal?

In Java, is the new BigDecimal from another bigDecimal.toString () always equal? for instance

BigDecimal a = new BigDecimal("1.23"); BigDecimal b = new BigDecimal(a.toString()); System.out.println(a.compareTo(b) == 0); // always true? 

I know that BigDecimal is immutable, but I want to know if there is a good way to clone a BigDecimal object?

+6
source share
3 answers

Yes, you can assume so. From BigDecimal.toString docs

If this string representation is converted back to BigDecimal using the constructor of BigDecimal(String) , then the original value will be restored.

However, you can safely share the same object, because it is immutable and copying is not required

+7
source

One easy way is to add ZERO

 BigDecimal a = new BigDecimal("1.23"); BigDecimal b = a.add(BigDecimal.ZERO); 
+3
source

Just a note: BigDecimal is not final, so it can be extended with a mutable class. Therefore, in some use cases, a protective copy is required.

You can use the BigDecimal.toString () method:

  * There is a one-to-one mapping between the distinguishable * {@code BigDecimal} values and the result of this conversion. * That is, every distinguishable {@code BigDecimal} value * (unscaled value and scale) has a unique string representation * as a result of using {@code toString}. If that string * representation is converted back to a {@code BigDecimal} using * the {@link #BigDecimal(String)} constructor, then the original * value will be recovered. 

Here is a sample code that creates a protective copy of BigDecimal:

 public static BigDecimal safeInstance(BigDecimal val) { return val.getClass() == BigDecimal.class ? val : new BigDecimal(val.toString()); } 

But does that make sense? If a class extends the BigDecimal class, you cannot be sure that it does not extend its toString () method without abiding by the contract ...

Perhaps it is better to invalidate any BigDecimal extension:

 public static BigDecimal safeInstance(BigDecimal val) { if (val.getClass() != BigDecimal.class) { //TODO throw exception } return val; } 
0
source

All Articles