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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20358955/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 16:00:35  来源:igfitidea点击:

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

vb.netrounding

提问by Joseph Kim

If I want to round 3.32 to 3.30 and 3.38 to 3.40, how can I do that?

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

I tried math.round(), but I couldn't do that.

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

回答by Rahul Tripathi

You are probably looking for Math.Round Methodin VB.NET

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

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

将值舍入到最接近的整数或指定的小数位数。

Try like this:

像这样尝试:

Math.Round(3.32, 1)

or this:

或这个:

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

回答by drew_w

You can specify the number of significant figures in the Math.Round routine (overload). I'm used to C# but the VB.NET syntax should be something like:

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

Math.Round(3.44, 1)

See "http://msdn.microsoft.com/en-us/library/aa340228(v=vs.71).aspx" for more information.

有关详细信息,请参阅“ http://msdn.microsoft.com/en-us/library/aa340228(v=vs.71).aspx”。

回答by Rahil

Adding to the previous solutions, to get two-digit correct decimal values, use this:

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

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

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

回答by Steven Doggart

Like this:

像这样:

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

The first parameter is the number to round. The second parameter specifies how many digits to round to after the decimal point. The third parameter specifies that you want to use standard away-from-zero rounding rather than bankers rounding).

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