C#四捨五入

  • 13872
  • 0

C#四捨五入,放送給各位Round Function

自製的C#四捨五入,放送給各位。Round Function

 

01 public static Double Round(Double a_Value, int a_Places)
02         {
03             Double l_RT, l_XS;
04             l_XS = 1;
05             if (a_Places >= 0)
06             {
07                 for (int i = 1; i <= a_Places; i++)
08                 {
09                     l_XS = l_XS * 10;
10                 }

11             }

12             else
13             {
14                 for (int i = a_Places; i < 0; i++)
15                 {
16                     l_XS = l_XS * 0.1;
17                 }

18             }

19             l_RT = Math.Floor(Math.Abs(a_Value) * l_XS + 0.5) / l_XS;
20             
21             if (a_Value >= 0)
22                 return l_RT;
23             else return 0 - l_RT;
24         }

測試結果 Test results

Round(123.4567,3)= 123.457
Round(123.4567,2)= 123.46
Round(123.4567,-1)= 123.5
Round(123.4567,0)= 123
Round(122.4567,3)= 122.457
Round(122.4567,2)= 122.46
Round(122.4567,1)= 122.5
Round(122.4567,0)= 122
Round(-123.4567,3)= -123.457
Round(-123.4567,2)= -123.46
Round(-123.4567,1)= -123.5
Round(-123.4567,0)= -123
Round(-122.4567,3)= -122.457
Round(-122.4567,2)= -122.46
Round(-122.4567,1)= -122.5
Round(-122.4567,0)= -122
Round(124.4567,-3)= 0
Round(124.4567,-2)= 100
Round(124.4567,-1)= 120
Round(125.4567,-2)= 100
Round(125.4567,-1)= 130
Round(-124.4567,-3)= 0
Round(-124.4567,-2)= -100
Round(-124.4567,-1)= -120
Round(-125.4567,-2)= -100
Round(-125.4567,-1)= -130