Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Long to String before converting to a BigDecimal

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.

like image 555
Lucas Paolotti Avatar asked Dec 10 '22 17:12

Lucas Paolotti


1 Answers

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 a BigDecimal which is exactly equal to 0.1 [...], but it is actually equal to 0.1000000000000000055511151231257827021181583404541015625. This is because 0.1 cannot be represented exactly as a double [...].

The String constructor, on the other hand, is perfectly predictable: writing new BigDecimal("0.1") creates a BigDecimal which is exactly equal to 0.1, as one would expect. Therefore, it is generally recommended that the String constructor be used in preference to this one.

like image 193
Tunaki Avatar answered Dec 23 '22 04:12

Tunaki