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.


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.)


Any of these help?

println(3.0/4.0)
println(3.toDouble/4.toDouble)

For the primitive types (Int, Float, Double etc), Scala follows the rules in Java.

If you write literal integers 3, 4, and so on, their expressions will remain as integers. So

println(3/4)

has an expression consisting of two integers so the result is an integer: 0.

If any of the values happens to be a Float instead of an Int, the whole expression widens to become a Float. The same is true for a Double. This widening happens almost completely automatically - you just have to give the compiler the hint of what you wanted, e.g.

println(3f/4)

widens to Float and

println(3.0/4)

widens to Double.

When using these language features in real programs, always think about the loss of precision that can occur. You've already noticed the integer division causing the loss of the decimal fraction in that case. But there's a different case for floating point that is illustrated here:

println(4f/3)

The actual result is held in a binary representation (using the IEEE754 standard) which has binary fractions, not decimal fractions, and so not able to hold 4f/3 without a small error.

scala> println(100f/99f * 99)
99.99999

You might have expected it to print 100. Sometimes this doesn't matter and sometimes it does. One very common case where it matters a lot is when dealing with monetary values. The rule of thumb is ALWAYS AVOID float and double for money: use BigDecimal instead, or just hold the number of pence as a Long perhaps, or sometimes resort to Strings (which play nicely with BigDecimal provided they are not parsed as Double values on the way).