天天看點

C# 保留小數位數的方法

Ø  前言

本文主要介紹 C# 中實作小數位數的保留,完成對小數位數四舍五入的幾種方法。

1.   使用 Math.Round() 方法

說明:

1)   其實使用 Math.Round() 方法,是根據國際标準(五舍六入)的方式進行取舍的。

2)   進1的情況有兩種:1)保留小數位後面第1位大于等于6;2)保留小數位後面第1位等于5,則第2位必須大于0。

double double1_1 = Math.Round(1.545, 0);            //2.0

double double1_2 = Math.Round(1.545, 1);            //1.5

double double1_3 = Math.Round(1.545, 2);            //1.54

double double1_4 = Math.Round(1.5451, 2);           //1.55

double double1_5 = Math.Round(1.546, 2);            //1.55

2.   使用 Decimal.Round() 方法

說明:小數取舍與 Math.Round() 方法相同。

decimal decimal2_1 = decimal.Round(1.545m, 0);      //2M

decimal decimal2_2 = decimal.Round(1.545m, 1);      //1.5M

decimal decimal2_3 = decimal.Round(1.545m, 2);      //1.54M

decimal decimal2_4 = decimal.Round(1.5451m, 2);     //1.55M

decimal decimal2_5 = decimal.Round(1.546m, 2);      //1.55M

3.   使用 ToString() + NumberFormatInfo

說明:标準的四舍五入法,更适合中國人的習慣哦。

NumberFormatInfo nfi3_1 = new NumberFormatInfo();

nfi3_1.NumberDecimalDigits = 0;

string str3_1 = 1.545d.ToString("N", nfi3_1);       //"2"

nfi3_1.NumberDecimalDigits = 1;

string str3_2 = 1.545d.ToString("N", nfi3_1);       //"1.5"

nfi3_1.NumberDecimalDigits = 2;

string str3_3 = 1.545d.ToString("N", nfi3_1);       //"1.55"

string str3_4 = 1.5451d.ToString("N", nfi3_1);      //"1.55"

string str3_5 = 1.546d.ToString("N", nfi3_1);       //"1.55"

4.   使用 ToString() + 格式化字元

string str4_1_1 = 1.545d.ToString("N0");            //"2"

string str4_1_2 = 1.545d.ToString("N1");            //"1.5"

string str4_1_3 = 1.545d.ToString("N2");            //"1.55"

string str4_1_4 = 1.5451d.ToString("N2");           //"1.55"

string str4_1_5 = 1.546d.ToString("N2");            //"1.55"

//ToString() 的簡單方法

string str4_2_6 = 1.545d.ToString("0");             //"2"

string str4_2_7 = 1.545d.ToString("0.0");           //"1.5"

string str4_2_8 = 1.545d.ToString("0.00");          //"1.55"

string str4_2_9 = 1.5451d.ToString("0.00");         //"1.55"

string str4_2_10 = 1.546d.ToString("0.00");         //"1.55"

5.   使用 String.Format() 方法

string str5_1 = string.Format("{0:N0}", 1.545d);    //"2"

string str5_2 = string.Format("{0:N1}", 1.545d);    //"1.5"

string str5_3 = string.Format("{0:N2}", 1.545d);    //"1.55"

string str5_4 = string.Format("{0:N2}", 1.5451d);   //"1.55"

string str5_5 = string.Format("{0:N2}", 1.546d);    //"1.55"

6.   将數字轉為“%”百分号字元串

string str6_1 = 0.545d.ToString("P", new NumberFormatInfo

{

    PercentDecimalDigits = 2,       //轉換後小數保留的位數,預設為2

    PercentPositivePattern = 1      //%号出現的位置:1 數字後面,2 數字前面,預設為0

}); //"54.50%"