calvin
calvin

Reputation: 2935

How can I convert Long from String in scala

I know I can parse from Long from String like the following

"60".toLong

or convert Long from Double like the following

60.0.toLong

or convert Long from a String of Double like the following

"60.0".toDouble.toLong

However, I can't do the following

"60.0".toLong

So my question is whether using .toDouble.toLong is a best practice, or should I use something like try ... catch ...?

Meanwhile, there is another question, when I try to convert a very large Long to Double, there maybe some precision loss, I want to know how to fix that?

"9223372036854775800.31415926535827932".toDouble.toLong

Upvotes: 0

Views: 1487

Answers (1)

Tim
Tim

Reputation: 27356

You should wrap the operation in a Try anyway, in case the string is not valid.

What you do inside the Try depends on whether "60.0" is a valid value in your application.

If it is valid, use the two-step conversion.

Try("60.0".toDouble.toLong) // => Success(60)

If it is not valid, use the one-step version.

Try("60.0".toLong) // => Failure(java.lang.NumberFormatException...)

Answer to updated question:

9223372036854775800.31415926535827932 is outside the range for a Double, so you need BigDecimal for that.

Try(BigDecimal("9223372036854775800.31415926535827932").toLong)

However you are very close to maximum value for Long, so if the numbers really are that large I suggest avoiding Long and using BigDecimal and BigInt.

Try(BigDecimal("9223372036854775800.31415926535827932").toBigInt)

Note that toLong will not fail if the BigDecimal is too large, it just gives the wrong value.

Upvotes: 5

Related Questions