且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何舍入到在C#中最接近的整数

更新时间:2023-01-29 11:14:26

查看官方文档更多。例如:

基本上你给 Math.Round 方法三个参数。

Basically you give the Math.Round method three parameters.


  1. 您要舍入的值。

  2. 您想保留值之后小数位数。

  3. 您可以调用使用AwayFromZero四舍五入的可选参数。没有它,'1.5'四舍五入为12来代替。

样code:

var roundedA = Math.Round(1.1, 0); // Output: 1
var roundedB = Math.Round(1.5, 0, MidpointRounding.AwayFromZero); // Output: 2
var roundedC = Math.Round(1.9, 0); // Output: 2

您需要 MidpointRounding.AwayFromZero 是你想被围捕了0.5的值。不幸的是,这不是默认行为 Math.Round()

You need MidpointRounding.AwayFromZero is you want a .5 value to be rounded up. Unfortunately this isn't the default behavior for Math.Round().