Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Agile forum!

# round off

Girish Solanke
Greenhorn
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
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

Girish Solanke
Greenhorn
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 .......

Regards

marc weber
Sheriff
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

Tim McGuire
Ranch Hand
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
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!