Thread: How to round up floating number properly?

1. Member
Join Date
Jan 2012
Posts
6
Rep Power
0

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

2. Re: How to round up floating number properly?

Look at the round methods provided by the Math class, Math (Java Platform SE 6)

3. Senior Member
Join Date
Jan 2012
Posts
210
Rep Power
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).

4. Moderator
Join Date
Feb 2009
Location
New Zealand
Posts
4,712
Rep Power
15

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

5. Member
Join Date
Jan 2012
Posts
6
Rep Power
0

Re: How to round up floating number properly?

OK, Guys. Thank you so much. Got it. Much appreciated...

Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•