Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala Divide two integers and get a float result

If I do the following

 println(3/4)  >0 

I would like to get a decimal answer instead of an integer. Because of the way I am printing in my actual code I would prefer to cast within the println if that is possible.

like image 730
richsoni Avatar asked Jun 20 '12 16:06

richsoni


People also ask

Can integer be 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.

How do you find the float value after division?

Just use $value = (float)($x/$y); //Result will in float. Cheers!

How do you find the float value by dividing two integers?

Dividing an integer by an integer gives an integer result. 1/2 yields 0; assigning this result to a floating-point variable gives 0.0. To get a floating-point result, at least one of the operands must be a floating-point type. b = a / 350.0f; should give you the result you want.

How do you do double division in Scala?

In Scala, Double is a 64-bit floating point number, which is equivalent to Java's double primitive type. The %(x: Float) method is utilized to return the remainder when the given Double value is divided by the float value. Returns – Returns the remainder of the division of this value by x.


1 Answers

If you're typing the number, just type at least one of them as a float (I assume you mean Float not Double):

println(3f/4) 

If you already have the numbers in variables, convert at least one of them with toFloat

val x = 3 println(x.toFloat/4) 

(In each case, if you have at least one, the compiler will convert the other to Float to match.)

like image 153
Rex Kerr Avatar answered Sep 18 '22 23:09

Rex Kerr