2007/10/23

Round off in C# (updated)

How to round off in C#? Heres are what I know:

1.Create a method and perform some logics
Ex:
N = 24.12731 I want to show "24.13" only.
Step a. N*100 + 0.5 = 2413.231
Step b. Divide System.Math.Floor(2413.231) by 100
Step c. The result will be 24.13

2.Use ToString()
double d = 3.445;
d.ToString("0.00");  //3.45
d.ToString("0.0");  //3.4
d.ToString("0");  //3

3.Use System.Math.Round()
System.Math.Round(3.445, 2);  //3.44
System.Math.Round(3.445, 2, MidpointRounding.AwayFromZero)  //3.45

One thing needs to be cared of:
In some cases, the result from System.Math.Round() will be different from ToString(). For example:
double d = 0.2975;
System.Math.Round(d, 3)  //You will get 0.297
d.ToString("0.000")  //You will get 0.298

5 comments: