Scala Divide two integers and get a float result

纵然是瞬间 提交于 2020-04-29 06:22:17

问题


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.


回答1:


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




回答2:


Any of these help?

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



回答3:


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



来源:https://stackoverflow.com/questions/11123572/scala-divide-two-integers-and-get-a-float-result

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!