File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Beginning Java and the fly likes round off Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "round off" Watch "round off" New topic
Author

round off

Girish Solanke
Greenhorn

Joined: Mar 03, 2006
Posts: 13
Hi,

I want to round of integer to integer,
it means say i have one digit 46 then it should be rounded to 50,
& 44 should become 40.

same must be applicable to any no. of digit
Stan James
(instanceof Sidekick)
Ranch Hand

Joined: Jan 29, 2003
Posts: 8791
Old trick for ints from my COBOL days. To round to the nearest N add N-1, divide by N, multiply by N. To round up to nearest 10 ...

44 + 9 = 53
53 / 10 = 5
5 * 10 = 50

To round 45 up and 44 down, add N/2 instead of N

44 + 5 = 49
49 / 10 = 4
4 * 10 = 40

45 + 5 = 50
... -> 50


A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi
Girish Solanke
Greenhorn

Joined: Mar 03, 2006
Posts: 13
Hi Stan James,

You are right,

But in run time I may not know whether that digit is two digit or three or more than that ........
In that case How would i come know
&
Again I am expecting any inbuild function from java clases .......

Thanks for reply.....


Regards
marc weber
Sheriff

Joined: Aug 31, 2004
Posts: 11343

"Girish S,"

Please revise your display name to meet the JavaRanch Naming Policy. To maintain the friendly atmosphere here at the ranch, we like folks to use a first and a last name.

You can edit your name here. Thank you for your prompt attention!

-Marc


"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer
sscce.org
Tim McGuire
Ranch Hand

Joined: Apr 30, 2003
Posts: 820

I divide the number which I wish to round by 10:

46 / 10 = 4.6

Math.round(4.6) = 5

and restore it by multiplying by 10:
5 * 10 = 50.
Stan James
(instanceof Sidekick)
Ranch Hand

Joined: Jan 29, 2003
Posts: 8791
Girish, Tim's method or mine will work with numbers of any size to very near the max or min integer values. Try em and see!
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: round off
 
Similar Threads
rounding
compilation error
howto round integer ?
need a double returned with 2 decimal points
Recursion Problem