How to round up floating number properly?
I just found out that converting a floating number to integer, will round down in Java, for example:
When I try:
float fl = 45.7;
int i = (int) fl;
Or
Float fl = New Float(45.7);
int i = fl.intValue()
The results are = 47! How can I round it up to the nearest integer? For example 45.7 -> 46, 45.3 -> 45.
I am sorry if I sound dumb here, I am not, but I am used to other language (which can do this easily), and the book I use do not explain this one in enough detail. Thank you...
Re: How to round up floating number properly?
Look at the round methods provided by the Math class, Math (Java Platform SE 6)
Re: How to round up floating number properly?
float fl = 45.7f;
int i = Math.round(fl);
but if You have double, need typecast to int:
double fl = 45.7;
int i = (int)Math.round(fl);
Because, Math.round(fl) return (long)Math.floor(fl + 0.5) and floor(fl + 0.5) return double floor(double fl).
Re: How to round up floating number properly?
And maybe look at the formatting offered by NumberFormat and the printf() family (in String, PrintStream etc).
I mention this because often people speak of "rounding" a number when they are really concerned with getting some human friendly representation of it. The latter task (which is formatting) need not involve rounding a value (and hence making it less accurate).
Re: How to round up floating number properly?
OK, Guys. Thank you so much. Got it. Much appreciated...