I have two Int
values in Scala.
scala> val a = 3
a: Int = 3
scala> val b = 5
b: Int = 5
Now, I want to divide them and get Float. With as little boilerplate as possible.
If I do a/b
, I get
scala> a/b
res0: Int = 0
I cannot do simple Java (float)
.
scala> ((Float)a)/b
<console>:9: error: value a is not a member of object Float
((Float)a)/b
^
What should I do?
Divide and Assignment Operator (/=) Divide And Assignment Scala Operator divides the first operand by the second, and then assigns the result to the left operand.
The % (integer divide) operator divides two numbers and returns the integer part of the result. The result returned is defined to be that which would result from repeatedly subtracting the divisor from the dividend while the dividend is larger than the divisor.
Dividing two integers always results in an integer. If you want to get a decimal result from dividing two integers, use floating point division.
If one of the operands in you division is a float and the other one is a whole number ( int , long , etc), your result's gonna be floating-point. This means, this will be a floating-point division: if you divide 5 by 2, you get 2.5 as expected. Follow this answer to receive notifications.
The following line followed by its result should solve your problem.
scala> a.toFloat/b
res3: Float = 0.6
Alternative answer that uses type ascription:
scala> (a:Float)/b
res0: Float = 0.6
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With