C#之如何实现真正的四舍五入
c#之如何实现真正的四舍五入
c#实现真正的四舍五入
c#中的math.round()直接使用的话,实际上是:四舍六入五取偶,并不是真正意义上的四舍五入。
例如 我取2位小数 17.365
会变成17.36 很苦恼
实现真正四舍五入需要用到 midpointrounding.awayfromzero 枚举项,同时传入的数值类型必须是decimal类型:
用法示例:
decimal dd= math.round((decimal)66.545, 2, midpointrounding.awayfromzero);
还有2种比较残暴的 写个函数 正负数都可以四舍五入或者负数五舍六入
double round(double value, int decimals)
{
if (value < 0)
{
return math.round(value + 5 / math.pow(10, decimals + 1), decimals, midpointrounding.awayfromzero);
}
else
{
return math.round(value, decimals, midpointrounding.awayfromzero);
}
}
double round(double d, int i)
{
if(d >=0)
{
d += 5 * math.pow(10, -(i + 1));
}
else
{
d += -5 * math.pow(10, -(i + 1));
}
string str = d.tostring();
string[] strs = str.split('.');
int idot = str.indexof('.');
string prestr = strs[0];
string poststr = strs[1];
if(poststr.length > i)
{
poststr = str.substring(idot + 1, i);
}
string strd = prestr + "." + poststr;
d = double.parse(strd);
return d;
}
参数:d表示要四舍五入的数;i表示要保留的小数点后为数。
其中第二种方法是正负数都四舍五入,第一种方法是正数四舍五入,负数是五舍六入。
备注:个人认为第一种方法适合处理货币计算,而第二种方法适合数据统计的显示。
c#简单四舍五入函数
public int getnum(double t) {
double t1;
int t2;
string[] s = t.tostring().split('.');
string i = s[1].substring(0, 1);//取得第一位小数
int j = convert.toint32(i);
if (j >= 5)
t1 = math.ceiling(t); //向上 转换
else
t1 = math.floor(t);// 向下 转换
t2 = (int)t1;
return t2;
}
- convert.toint32(1.2) 为四舍五入 的强制转换 但是 0.5时候 会为 0
- (int) 1.2 是向下强制转换既math.floor(),1.2转换后为1;
- math.ceiling(1.2)则是向上转换,得到2。
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持硕编程。


