I have to convert a Long (Object one, contained in the variable 'longValueToConvert') to a BigDecimal.
I would have done something like this :
new BigDecimal(longValueToConvert)
But i've read that this cast could induce errors in the conversion and that it is prefered to cast the Long to a String before using it to the BigDecimal constructor.
new BigDecimal(longValueToConvert.toString())
Is it Ok to use the first one or the second one would be preferable ? I use Java 8.
You heard wrong. There is no conversion error from the BigDecimal(long)
constructor. A long
can be represented exactly and there is no problem making a BigDecimal
out of it.
You need to be careful only when you use the BigDecimal(double)
constructor. This is because some double
values can't be represented exactly. From the documentation:
The results of this constructor can be somewhat unpredictable. One might assume that writing
new BigDecimal(0.1)
in Java creates aBigDecimal
which is exactly equal to0.1
[...], but it is actually equal to0.1000000000000000055511151231257827021181583404541015625
. This is because0.1
cannot be represented exactly as adouble
[...].The
String
constructor, on the other hand, is perfectly predictable: writingnew BigDecimal("0.1")
creates a BigDecimal which is exactly equal to0.1
, as one would expect. Therefore, it is generally recommended that the String constructor be used in preference to this one.