Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Int division in scala

Tags:

scala

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?

like image 681
Karel Bílek Avatar asked Jul 03 '12 01:07

Karel Bílek


People also ask

How do you divide in Scala?

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.

What is int division?

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.

Can INT integers be divided?

Dividing two integers always results in an integer. If you want to get a decimal result from dividing two integers, use floating point division.

What is int divided by float?

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.


2 Answers

The following line followed by its result should solve your problem.

scala> a.toFloat/b
res3: Float = 0.6
like image 173
Karel Bílek Avatar answered Oct 15 '22 07:10

Karel Bílek


Alternative answer that uses type ascription:

scala> (a:Float)/b
res0: Float = 0.6
like image 18
Kristian Domagala Avatar answered Oct 15 '22 09:10

Kristian Domagala