关于四舍五入:如何在VB.NET中四舍五入到任意小数位数(即从3.32到3.30)?

How do I round to an arbitrary number of decimals (i.e., from 3.32 to 3.30) in VB.NET?

如果我想将3.32舍入到3.30,并将3.38舍入到3.40,该怎么办?

我尝试了math.round(),但是我做不到。


添加到前面的解决方案中,要获得两位数的正确十进制值,请使用以下命令:

1
2
3
4
5
FormatNumber((Math.Round(3.32, 1, MidpointRounding.AwayFromZero)), 2)
' Returns 3.30

FormatNumber((Math.Round(3.38, 1, MidpointRounding.AwayFromZero)), 2)
' Returns 3.40


您可以在Math.Round例程(重载)中指定有效数字的数量。 我已经习惯了C#,但是VB.NET语法应该类似于:

1
Math.Round(3.44, 1)

有关更多信息,请参见" http://msdn.microsoft.com/en-us/library/aa340228(v=vs.71).aspx"。


您可能正在VB.NET中寻找Math.Round方法

Rounds a value to the nearest integer or to the specified number of
fractional digits.

尝试这样:

1
Math.Round(3.32, 1)

或这个:

1
2
Math.Round(3.32, 1, MidpointRounding.AwayFromZero)
Math.Round(3.38, 1, MidpointRounding.AwayFromZero)


像这样:

1
2
Math.Round(3.32, 1, MidpointRounding.AwayFromZero)  ' Returns 3.3
Math.Round(3.38, 1, MidpointRounding.AwayFromZero)  ' Returns 3.4

第一个参数是要舍入的数字。 第二个参数指定小数点后四舍五入到几位数。 第三个参数指定您要使用标准的非零舍入而不是银行家舍入。