-
August 31st, 2010, 01:46 AM
#1
Rounding off number
Hello guys,
How can I get the round off number disregarding the next number specify in length of decimal places in math.round. Example, I want to round off 1.499 to 1.49 not 1.5.
My program has a condition if the decimal places is more than .05, it will add 1. example 1.0521 will become 2. But if its 1.0498 will become 1.
It is possible guys?
Thanks in advance.
-
August 31st, 2010, 02:17 AM
#2
Re: Rounding off number
For as far I know, this is not possible (please correct me if I'm wrong)
But offcourse, you could write your own method to do this. Try the next:
Code:
public int Round(double d) {
int temp = (int)d;
double rest = d - temp;
int result = 0;
if (rest >= 0.05)
result = 1;
return result + temp;
}
...
int i = Round(1.05); //will result in 2
i = Round(1.049); //will result in 1
-
August 31st, 2010, 02:26 AM
#3
Re: Rounding off number
Rounding:
Code:
double d = 1.499;
double twoDigitsRound = double.Parse(String.Format("{0:0.##}", d)); //1.5, since it's closer to 1.50 than to 1.49...
double fourDigitsRound = double.Parse(String.Format("{0:0.####}", d)); //1.499
//etc...
Flooring:
Code:
Floor(this double d, int numDigits)
{
return (int)(d * Math.Pow(10, numDigits)) / Math.Pow(10, numDigits);
//if Math.Pow(int,int) returns int and not double, make sure you cast it back to double
}
...
double d = 1.499;
double twoDigitsRound = d.Floor(2); //1.49
double fourDigitsRound = d.Floor(4); //1.499
//etc...
-
August 31st, 2010, 03:20 AM
#4
Re: Rounding off number
thanks dannystommen and talikag, for the idea. It works already
-
August 31st, 2010, 07:13 AM
#5
Re: Rounding off number
Please mark your thread resolved. It is explained here :
http://www.codeguru.com/forum/showthread.php?t=401115
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|