locked
How to limit decimal places after a double?

    Question

  • Hi, everyone

    E.g.

    double op, Q = 0.112233445566778899, H = 100.0,  k = 20000.0; 

    op = Q * H * k;

    Can the decimal places of "op" be limited to ..... let say 6 decimal places?

    Sunday, December 31, 2006 3:04 PM

Answers

  • Try this:
          string s = string.Format("{0:N6}", Q);

    Sunday, December 31, 2006 3:08 PM

All replies

  • Try this:
          string s = string.Format("{0:N6}", Q);

    Sunday, December 31, 2006 3:08 PM
  • Or if you want the double itself to be limited you could use this method:



            //Trim double v to n decimal places
            private double trim(double v, double n)
            {
                double p = Math.Pow(10, n);
                return (Math.Round(v * p)) / p;
            }


     

    or better still...

    Math.Round(double v, int n)  where n is the number of decimal places desired.

     

    Sunday, December 31, 2006 3:33 PM
  • Thanks jrboddie for the solution. It needed a little tweak:

    V = Math.Round(V,n);

    Using string is only good for displaying as a label n stuff like that, in my case I need to do additional calculation so using string is out of the picture.But thanks anyway.

    Happy New Year to all !!!!!! :-)

    Tuesday, January 02, 2007 2:22 PM
  • Hmm, code like that cannot work.  Here's an example:

          double d1 = 0.10999300000001;
          double d2 = Math.Round(d1, 6);
          Console.WriteLine("{0:N20} rounds to {0:N20}", d1, d2);

    Use the Decimal type to avoid problems like this.
    Tuesday, January 02, 2007 3:18 PM
  • OMG. Tried your code and it didn't work. Thanks for the tip. Maybe because its a console application?

    This works:

    double d1 = 0.10999300000001;

    d1 = Math.Round(d1, 6);

    Console.WriteLine("{0:N20} rounds to {0}", d1);

     

    Anyway, my line of code above works fine in my application. I would not need to assign d2 to a rounded off d1. I only need to control the decimal place after my calculation. Furthermore, I could even store it into my database.

     

    Tuesday, January 02, 2007 3:39 PM
  • Nope.  Sorry, but you're fooling yourself.  With the {0} format specifier, you're asking .NET to round the value for you when it generates the display string.  The actual value is still un-rounded.  The key problem here is that the double type simply doesn't have enough accuracy to properly round.  First ask yourself if you truly want to perform the arithmetic on rounded values.  It is rarely required, you typically only need to display a rounded value, not calculate with one.  If you truly need a rounded value for your math, avoid the double type and use Decimal instead. 
    Tuesday, January 02, 2007 4:05 PM
  • Actually, you are right. I only need to display a rounded value and not calculate with one. Thanks for the help.
    Wednesday, January 03, 2007 12:15 AM