Rather than an "8.75" returned.
Which method? Thanks.
Rather than an "8.75" returned.
Which method? Thanks.
Use
Math.floor(..)
Returns the largest (closest to positive infinity) double value that is less than or equal to the argument and is equal to a mathematical integer.
Or, if you need to manipulate ints, not doubles, then simply assign to int:
int a = 35 / 4;
Actually, if you work with the numbers directly, or with int variables, you will get an int
result automatically.
using
int myInt = (int) Math.floor(value);
8.75 will be rounded to 8. Casting to int removes decimals in case value is a double.
If I'm not completely wrong, 35/4
always evaluates to 8. Even in
double result = 35 / 4;
you will get this result (as double, i.e. 8.0
). This is because 35
and 4
are both integers and therefore integer division is applied. The expression is first evaluated as integer and only the result is cast to a double value.
On the other hand, if you want the correct result 8.75
you' ll have to write
double result = 35. / 4;
in order to force floating point division to be applied. This is a common pitfall by the way.
Of course, if you have double values, like in
double a = 35;
double b = 4;
you need to either explicitely cast to an int
or use Math.floor()
as suggested in previous posts.
Several very helpful answers here. Thank you.
That said, I'd accept more than one answer--or none, because that's the way SO is set up. So thanks all. Much appreciated. I'll up your answers, but unfortunately no green check (much as I'd like). I'd be playing favorites.
Thanks again all for your help. (If you want to recommend among yourselves which I should 'accept', I'd be happy to consider.)
UPDATED: Okay, I accepted one.
int x = 35/4
integer division causes 8 to be returned instead of 8.75