Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is new a BigDecimal from another bigDecimal.toString() always equals?

Tags:

java

In Java, is new a BigDecimal from another bigDecimal.toString() always equals? For example

    BigDecimal a = new BigDecimal("1.23");
    BigDecimal b = new BigDecimal(a.toString());

    System.out.println(a.compareTo(b) == 0); // always true?

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

like image 800
andyf Avatar asked Oct 28 '15 01:10

andyf


2 Answers

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

If that string representation is converted back to a BigDecimal using the BigDecimal(String) constructor, then the original value will be recovered.

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

like image 136
Sleiman Jneidi Avatar answered Sep 27 '22 00:09

Sleiman Jneidi


One simple way would be to add ZERO

BigDecimal a = new BigDecimal("1.23");
BigDecimal b = a.add(BigDecimal.ZERO);
like image 42
user3871424 Avatar answered Sep 23 '22 00:09

user3871424