Lucas Paolotti
Lucas Paolotti

Reputation: 43

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.

Upvotes: 4

Views: 1372

Answers (2)

Tunaki
Tunaki

Reputation: 137084

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.

Upvotes: 12

ha9u63a7
ha9u63a7

Reputation: 6824

You can try this:

new BigDecimal(longValueToConvert.longValue())

This works fine. I believe your concern should be when representing floating point numbers as the precision matters there. e.g. when you are using BigDecimal (double) or BigDecimal(float) constructors. Do you have these scenarios? Also, the name here tells you everything. Long to any floating point number is not a problem, but the coming from the other directions requires care.

Upvotes: 1

Related Questions