tittapo
asked on
Rounding integer value
How can can I round integer values f.ex.
768 to 800 and 732 to 700 or 56 to 60 ...
768 to 800 and 732 to 700 or 56 to 60 ...
ASKER
hey omok.
your code gave me number 689 when I called it with 689 not 700.
private int round( double num )
{
if ( num >= 10 ) {
return round( (double)num / 10 ) * 10;
}
return (int)Math.round(num);
}
your code gave me number 689 when I called it with 689 not 700.
private int round( double num )
{
if ( num >= 10 ) {
return round( (double)num / 10 ) * 10;
}
return (int)Math.round(num);
}
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
Comment.
Thank' s for answers.
Actually that code was usuful for my purpose.
if ((maxnumber>=100) && (maxnumber<1000))
{
maxnumber = (int)(maxnumber/100)*100;
}
if ((maxnumber>=10) && (maxnumber<100))
{
maxnumber = (int)(maxnumber/10) * 10;
}
Thank' s for answers.
Actually that code was usuful for my purpose.
if ((maxnumber>=100) && (maxnumber<1000))
{
maxnumber = (int)(maxnumber/100)*100;
}
if ((maxnumber>=10) && (maxnumber<100))
{
maxnumber = (int)(maxnumber/10) * 10;
}
tittapo,
Are you sure my method doesn't work?
I have written a test program and tested it before I posted it here???
I am using JDK1.1.7 on NT4
Are you sure my method doesn't work?
I have written a test program and tested it before I posted it here???
I am using JDK1.1.7 on NT4
tittapo,
I don't think your code will work as (maxnumber/10) will always round down because you are doing Integer division.
Try 49, it will give you 40 instead of 50.
I don't think your code will work as (maxnumber/10) will always round down because you are doing Integer division.
Try 49, it will give you 40 instead of 50.
public static int round (int i)
{
if (i >= 100)
{
int mod = i % 100;
return (mod >= 50)?(i + (100 - mod)):( i - mod);
}
else
{
int mod = i % 10;
return (mod >= 5)?(i + (10 - mod)):( i - mod);
}
}
2-nd attempt.
Cheers.
{
if (i >= 100)
{
int mod = i % 100;
return (mod >= 50)?(i + (100 - mod)):( i - mod);
}
else
{
int mod = i % 10;
return (mod >= 5)?(i + (10 - mod)):( i - mod);
}
}
2-nd attempt.
Cheers.
private int round( double num )
{
if ( num >= 10 ) {
return round( (double)num / 10 ) * 10;
}
return (int)Math.round(num);
}
Hope this helps.