C# 数据处理——(包括但不限)浮点数设置小数点后位数

常用简单的有四种方法:

(这里介绍对浮点数处理,同样的对其他类型如双浮点数double、int等数据类型处理方法的思路也差不多。)

1、使用数学函数集合Mathf运算符:Mathf.Round();//浮点数四舍五入取整,如果舍去位是数字5,不管个数位是偶数还是奇数,将返回偶数。

float a = Mathf.Round(2.4567f);//结果为2
float b = Mathf.Round(2.5123f);//结果为2,小数位是5,个数位在2,3之间取偶数2
float c = Mathf.Round(3.4521f);//结果为3
float d = Mathf.Round(3.505f);//结果为4,小数位是5,个数位在3,4之间取偶数4
float e = Mathf.Round(3.622f);//结果为4

float num1 = Mathf.Round(floatValue * 10) /10;//保留小数点后一位
float num2 = Mathf.Round(floatValue * 100) /100;//保留小数点后两位

类似的还有:Mathf.Floor();Mathf.FloorToInt();Mathf.RoundToInt();等,详情可查unity脚本手册Mathf函数

2、使用Math类方法:Math.Round(Double num);或Math.Round(Double num1,Int32 num2);//num和num1是要处理的数,num2是设置保留小数点的位数

//四舍五入结果参考上面的Mathf.Round或Math文档
//float与double之间显式转换(强制转换)
float x = (float)Math.Round((double)x, 1);//将 x 后小数点位数指定为1
float x = (float)Math.Round((double)x, 2);//将 x 后小数点位数指定为2

类似的还有:Math.Round(Double,MidpointRounding);Math.Round(Decimal num);Math.Round(Decimal num1,Int32 num2);等详情可查看.Net的Math类文档

3、使用String.Format()方法:String.Format(string value,F1);或String.Format(string value,F2);//字符串的格式化为小数形式,F1保留小数点后一位,F2保留小数点后2位

string.Format("{0:F}",5.1261);  //5.13,默认保留两位小数且截取时自动四舍五入
string.Format("{0:f1}",5.1261); //5.1
string.Format("{0:F2}",5.1261);  //5.13
string.Format("{0:F3}",5.1261);  //5.126

//字符串与浮点数之间强制转换
float value = float.Parse(string.Format("{0:f1}", getValue));//保留一位小数
float value = float.Parse(string.Format("{0:f2}", getValue));//保留两位小数

类似的还有:string.Format("{0:N}", stringValue) ;string.Format("{0:###.##}",stringValue);等 详情可查看.Net的String.Format 方法文档

4、使用value.ToString()方法:value.ToString("0.0");或value.ToString("F2") ;

float value = float.Parse(getValue.ToString("0.0"));//保留小数点后一位
float value = float.Parse(getValue.ToString("0.00"));//保留小数点后两位

同string.Format()方法,还有其他多种格式。

猜你喜欢

转载自blog.csdn.net/weixin_43908355/article/details/115203415