asp教程.net c#保留小數位的方法集合
//2.保留n位,四捨五入 .
decimal d= decimal.round(decimal.parse("0.55555"),2);
//3.保留n位四捨五入
math.round(0.55555,2)
//4,保留n位四捨五入
double dbdata = 0.55555;
string str1 = dbdata.tostring("f2");//fn 保留n位,四捨五入
//5.保留n位四捨五入
string result = string.format("{0:n2}", 0.55555);//2位
string result = string.format("{0:n3}", 0.55555);//3位
//6. 保留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