CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 5 of 5
  1. #1
    Join Date
    Jul 2006
    Location
    Mnila, Philippines
    Posts
    171

    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.

  2. #2
    Join Date
    Sep 2008
    Location
    Netherlands
    Posts
    865

    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

  3. #3
    Join Date
    Jan 2007
    Posts
    491

    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...

  4. #4
    Join Date
    Jul 2006
    Location
    Mnila, Philippines
    Posts
    171

    Re: Rounding off number

    thanks dannystommen and talikag, for the idea. It works already

  5. #5
    Join Date
    Jul 2001
    Location
    Sunny South Africa
    Posts
    11,283

    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
  •  





Click Here to Expand Forum to Full Width

Featured