• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

round off

 
Girish Solanke
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
"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
IntelliJ IDE Tomcat Server VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic