how to fix decimal places?

  • Thread starter Thread starter Ron
  • Start date Start date
R

Ron

Greetings,

int i = 1, j = 6;
double k = (double)i/j;
Console.WriteLine(k.ToString());
Console.WriteLine(string.Format(k.ToString(), "0.00"));

both yield 0.166666666666667

how can I make it yield 0.17? I know there is some
method, I just can't think of it.


Thanks,
Ron
 
I found this so far, is there a more correct method?

int i = 1, j = 6;
double k = (double)i/j;
decimal rounded = decimal.Round((decimal)k, 2);
Console.WriteLine(rounded.ToString());

yields 0.17
 
Hi Ron! :O)

you should take a look at String.Format() method's help.. it is not the same
as the Format$() method of VB.

ToString() is the method you were looking for (sooo close ;O):
//***
Console.WriteLine(((double)5.2345345).ToString("0.00"));
Console.ReadLine();
//***
 
the decimal.Round() method (and some others i guess) uses a algorithm named
"Banker's Rounding" which might not give you the result you expect..

ex :
//***
Console.WriteLine(decimal.Round(((decimal)0.5), 0).ToString());
Console.WriteLine(decimal.Round(((decimal)1.5), 0).ToString());
Console.WriteLine(decimal.Round(((decimal)2.5), 0).ToString());
Console.ReadLine();
//***

returns :
0
2
2

see this link for more information about this topic
http://support.microsoft.com/kb/196652/en-us


besides, as you might know, there is a huge difference between Rounding a
value (loosing precision) and Formatting a value (showing a value in a human
readable format), thus ToString() is the way go.
//***
Console.WriteLine(((double)0.5).ToString("0"));
Console.WriteLine(((double)1.5).ToString("0"));
Console.WriteLine(((double)2.5).ToString("0"));
Console.ReadLine();
//***

returns :
1
2
3
 
Back
Top