Reputation: 1009
Given two numbers like so
val a: Any = 1
val b: Any = 2.3
How can I generically compare these two numbers (regardless if one of these numbers is a Double
, Long
, Float
etc.)?
Most of the solutions with implicits don't work since both values have been casted to Any
.
Upvotes: 0
Views: 47
Reputation: 9100
As both can be seen as java.lang.Number
s, you can cast them to them and compare their doubleValue
s:
(a.asInstanceOf[Number]).doubleValue < (b.asInstanceOf[Number]).doubleValue
Scala fiddle, Scala JS fiddle.
(Be careful with Double.NaN
s and large long values (thanks @PeterNeyens for reminding). In case you have to handle longs too, you should use a more complex logic.)
Upvotes: 2