Reputation: 576
I have a parser class which uses Apache POI to parse Excel files.
When a cell contains 1.0
, I would like to convert it to String "1"
.
And when I get 1.1
I would like to parse it to "1.1"
How to do that ?
I have try some experiments without success like that:
try
doubleValue.toInt
catch
{
case _ => doubleValue.toString
}
Or by using the Integer.parseInt()
method.
Upvotes: 0
Views: 179
Reputation: 7373
The following code returns an Int
if possible, otherwise a Double
if (doubleValue.isValidInt)
doubleValue.toInt
else
doubleValue
You must beware that the common type between the two is AnyVal
, and sometimes you should declare it explicitly to avoid the compiler to reconvert automatically the Int
result to a Double
.
P.S. if the outcome must be a String
, you can pack the above code in a method and call toString
on the result.
Upvotes: 4