總結C#保留小數位元

來源:互聯網
上載者:User

本文向大家介紹C#保留小數位,可能好多人還不瞭解C#保留小數位,沒有關係,看完本文你肯定有不少收穫,希望本文能教會你更多東西。

1.簡單的例子

 
    System.Globalization.NumberFormatInfo provider = new System.Globalization.NumberFormatInfo();       provider.NumberDecimalDigits =intDecLength; //要設定的小數位數       double strCashAmt=Convert.ToDouble(this.txtCashAmt.Text); //先把控制項內的值轉成double            this.txtCashAmt.Text = strCashAmt.ToString("N",provider); //再利用ToString函數格式化小數位數  


2.C#保留小數位N位,四捨五入 .

    decimal d= decimal.Round(decimal.Parse("0.55555"),2);  


3.C#保留小數位N位四捨五入

Math.Round(0.55555,2)  


4,C#保留小數位N位四捨五入

 
    double dbdata = 0.55555;       string str1 = dbdata.ToString("f2");//fN 保留N位,四捨五入  


5.C#保留小數位N位四捨五入

 
    string result = String.Format("{0:N2}", 0.55555);//2位            string result = String.Format("{0:N3}", 0.55555);//3位  


6. C#保留小數位N位四捨五入

double s=0.55555;   result=s.ToString("#0.00");//點後面幾個0就保留幾位 


C#保留小數位元,及百分比符號的解決方案:

1、用NumberFormatInfo類來解決:

 
    System.Globalization.NumberFormatInfo provider = new System.Globalization.NumberFormatInfo();            provider.PercentDecimalDigits = 2;//小數點保留幾位元.       provider.PercentPositivePattern = 2;//百分比符號出現在何處.       double result = (double)1 / 3;//一定要用double類型.       Response.Write(result.ToString("P", provider));  


2、用toString方法.:

public string getRate(double hcount, double task)   {   string rValue;   string temp = "";    if (task == 0)   {   task = 1;   }    double db = (hcount / task) * 100;    if (hcount >= task)   {   rValue = "100%";   }   else   {   rValue = db.ToString("#0.#0") + "%";   }   return rValue;   }    string str1 = String.Format("{0:N1}",56789); //result: 56,789.0   string str2 = String.Format("{0:N2}",56789); //result: 56,789.00   string str3 = String.Format("{0:N3}",56789); //result: 56,789.000   string str8 = String.Format("{0:F1}",56789); //result: 56789.0   string str9 = String.Format("{0:F2}",56789); //result: 56789.00   string str11 =(56789 / 100.0).ToString("#.##"); //result: 567.89   string str12 =(56789 / 100).ToString("#.##"); //result: 567  


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.