四舍五入到C#
发布时间:2020-12-15 06:31:29 所属栏目:百科 来源:网络整理
导读:我没有看到我期望与Math.Round的结果. return Math.Round(99.96535789,2,MidpointRounding.ToEven); // returning 99.97 据了解MidpointRounding.ToEven,千分之五的位置应该使输出为99.96.不是这样吗? 我甚至尝试过这个,但是它也返回了99.97: return Math.
我没有看到我期望与Math.Round的结果.
return Math.Round(99.96535789,2,MidpointRounding.ToEven); // returning 99.97 据了解MidpointRounding.ToEven,千分之五的位置应该使输出为99.96.不是这样吗? 我甚至尝试过这个,但是它也返回了99.97: return Math.Round(99.96535789 * 100,MidpointRounding.ToEven)/100; 我失踪了 谢谢! 解决方法
你实际上并不在中点. MidpointRounding.ToEven表示如果你的号码是99.965,即99.96500000 [等],那么你会得到99.96.由于您传递给Math.Round的数字在该中点之上,所以它正在四舍五入.
如果您希望将您的号码缩小到99.96,请执行以下操作: // this will round 99.965 down to 99.96 return Math.Round(Math.Truncate(99.96535789*1000)/1000,MidpointRounding.ToEven); 嘿,这里有一个很方便的小功能来做上面的一般情况: // This is meant to be cute; // I take no responsibility for floating-point errors. double TruncateThenRound(double value,int digits,MidpointRounding mode) { double multiplier = Math.Pow(10.0,digits + 1); double truncated = Math.Truncate(value * multiplier) / multiplier; return Math.Round(truncated,digits,mode); } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |