CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 3 of 3
  1. #1
    Join Date
    Jan 2009
    Posts
    177

    Convert double to 4 decimal

    Hi,

    All the data that I retrieve from database contain 2 decimal, how can I convert it to 4 decimal? For example, one of the data retrieve from database is 172.28, but I would like to convert it to 4 decimal point which is 172.2800.


    Code:
    double unitprice = Convert.ToDouble(dtLoop1.Tables[0].Rows[DetailRow1]["UnitPrice"].ToString());
                                    decimal unitprice1 = 0.00m;
    
                                    unitprice1 = Convert.ToDecimal(unitprice);
                                    unitprice1 = (decimal)(unitprice);

  2. #2
    Join Date
    Jun 2008
    Posts
    2,477

    Re: Convert double to 4 decimal

    That doesn't make much sense really. When you are working with a 'decimal' you have a 128 bit quantity. There is absolutely no difference between "172.28" and "172.2800", they are the same number. If you need to format the output to 4 decimal places just use a format string in the ToString( ) call:

    Code:
    MessageBox.Show( myDecimal.ToString( ".0000" ) );
    BTW, I am unsure why you create a double (which is a floating point number), convert it to a decimal, and then cast it to a decimal...

  3. #3
    Join Date
    Feb 2009
    Location
    Atlanta, GA
    Posts
    17

    Re: Convert double to 4 decimal

    You can also use string.Format()

    Code:
    string.Format("Value: {0:F4}", unitPrice);

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