c# 小数点格式化
1.只要求保留N位不四舍5入
float f = 0.55555f;
int i =(int)(f * 100);
f = (float)(i*1.0)/100;
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就保留几位
1.ToString()方法
double d=12345678.2334;
Console.WriteLine(d.ToString("F2")); //1234.23
Console.WriteLine(d.ToString("###,###.00")); //12,345,678.23
2.Math.Round()方法
Math.Round(3.44, 1); //Returns 3.4.
Math.Round(3.45, 1); //Returns 3.4.
Math.Round(3.46, 1); //Returns 3.5.
Math.Round(3.445, 1); //Returns 3.4.
Math.Round(3.455, 1); //Returns 3.5.
Math.Round(3.465, 1); //Returns 3.5.
Math.Round(3.450, 1); //Returns 3.4.(补0是无效的)
Math.Round(3.4452, 2); //Returns 3.45.
Math.Round(3.4552, 2); //Returns 3.46.
Math.Round(3.4652, 2); //Returns 3.47.
"四舍六入五考虑,五后非零就进一,五后皆零看奇偶,五前为偶应舍 去,五前为奇要进一" 短一点的口诀叫“四舍、六入、五凑偶”
3.double.Parse()方法
double d=1.12345;
d=double.Parse(d.ToString("0.00")); //1.12
4.输出百分号
System.Globalization.NumberFormatInfo provider = new System.Globalization.NumberFormatInfo();
provider.PercentDecimalDigits = 2;//小数点保留几位数.
provider.PercentPositivePattern = 1;//百分号出现在何处.
double result = (double)1 / 3;//一定要用double类型.
Console.WriteLine(result.ToString("P", provider)); //33.33%
或 Console.WriteLine((result*100).ToString("#0.#0")+"%");
result = Convert.ToDouble(dValue).ToString("P");//得到小数点后2位的百分比,自动 加上%号;//9512.35%
result = Convert.ToDouble(strValue).ToString("f4");//保留小数点后4位; //95.1235
//要注意的一点是 Convert.ToDouble一定要是这种双精度的,不然会报错。
5.String.Format()方法
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