-1

If i have {"myparam": 12.8} and my request class has
Integer myparam;
myparam gets set to 12 instead of 13.
Why is it a floor instead of a rounding up?

Rann Lifshitz
  • 4,040
  • 4
  • 22
  • 42
stumped
  • 491
  • 3
  • 6
  • 19
  • 2
    Why should it round up when you provide a `double` instead of an `Integer`? It's probably worth noting that all JavaScript number types (this looks like JSON) are 64-bit floating bit numbers. – Elliott Frisch Mar 01 '18 at 04:47
  • 3
    This is because numbers are usually truncated instead of being rounded when converting to a "less precise" type (ex. double -> integer). – Nybbit Mar 01 '18 at 04:49
  • Nybbit, how do you know that double->integer involves a truncation? – stumped Mar 01 '18 at 04:54
  • 1
    @stumped Because JSON parsers use subclasses of `Number` internally which involves truncation. See: https://docs.oracle.com/javase/7/docs/api/java/lang/Number.html#intValue() – W.K.S Mar 01 '18 at 04:57
  • @stumped that's how the vast majority of programming languages handle the conversion from floating point to integer. It's a bit dense, but the [JLS specifies this behavior](https://docs.oracle.com/javase/specs/jls/se9/html/jls-4.html#jls-4.2.4): "*The Java programming language uses round toward zero when converting a floating value to an integer, which acts, in this case, as though the number were truncated, discarding the mantissa bits.*" – dimo414 Mar 01 '18 at 05:03

1 Answers1

1

This is the expected behaviour of requesting an int value from a Double (as seen in the Double API):

public abstract int intValue()
Returns the value of the specified number as an int. This may involve
rounding or truncation.
Returns:
the numeric value represented by this object after conversion to type int.

The simplest way to explain it - when getting an int from a double, everything right of and including the '.' is chopped of.

Rann Lifshitz
  • 4,040
  • 4
  • 22
  • 42