Search code examples
scalalistdivision

Scala division result 0


i am compiling this code and getting 0 on the division

println((MarkAnalysis.failAmount/Student.studentsId.length).toDouble + " " + MarkAnalysis.failAmount + " " + Student.studentsId.length)

I print it out to make sure that the division does not return zero, and

MarkAnalysis.failAmount = 14
MarkAnalysis.studentsId.length = 53

I dont understand why i get 0.0 on the result.


Solution

  • To hazzard a guess failAmount and studentId are both whole numbers (int or long), therefore the result is a whole number (i.e. int/int is int). Since 14<53 this would be 0 (14 doesn't fit even once in 53). Only after 0 is calculated it is converted to double.

    What You want to do is a double division, and therefore need to convert to double before doing the division by adding .toDouble to at least one variable (better add to all in expression), e.g.:

    MarkAnalysis.failAmount.toDouble/Student.studentsId.length.toDouble