-1

I saw the following post in stack overflow which is related to my question:

BigDecimal - to use new or valueOf

I understand it is recommended to use string constructor for BigDecimal But my question is once you have defined a bigDecimal with string, can you use that value later using valueof.

Could someone let me know if the following code is valid?

BigDecimal tipPercent = new BigDecimal("0.0");
if (tipState == TipSelection.FIFTEEN) {
    tipPercent = BigDecimal.valueOf(FIFTEEN);
}

Thanks!

Community
  • 1
  • 1
an96
  • 31
  • 2
  • 5

2 Answers2

1

If you mean can you recover the String that you started with, then sort of: you can turn the BigDecimal into a String again with toString(). So in your case you could call

tipPercent.toString()

to get a String representation of tipPercent.

The reason I say "sort of" is that it might not be exactly what you put in, but it'll be equivalent. If you create a BigDecimal by passing it "00", you'll get back "0", but it represents the same number.

chiastic-security
  • 20,430
  • 4
  • 39
  • 67
1

It depends what Type of variable FIFTEEN is. valueOf in BigDecimal only works with double or long.

But you can reassign a BigDecimal to another BigDecimal no matter how it was created.

Justin
  • 1,356
  • 2
  • 9
  • 16