vb.net 在 Visual Basic 中四舍五入一个数字
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1228469/
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
Rounding a number down in Visual Basic
提问by Paul
I have a Visual Basic application that needs to round a number down, for example, 2.556 would become 2.55 and not 2.26.
我有一个需要向下舍入数字的 Visual Basic 应用程序,例如,2.556 将变为 2.55 而不是 2.26。
I can do this using a function to strip off the characters more than 2 right from the decimal point using this:
我可以使用一个函数来做到这一点,使用这个函数从小数点开始去除超过 2 个字符:
Dim TheString As String
TheString = 2.556
Dim thelength = Len(TheString)
Dim thedecimal = InStr(TheString, ".", CompareMethod.Text)
Dim Characters = thelength - (thelength - thedecimal - 2)
_2DPRoundedDown = Left(TheString, Characters)
Is there a better function to do this?
有没有更好的功能来做到这一点?
回答by Reed Copsey
You can do this with Math.Floor. However, you'll need to multiply * 100 and divide, since you can't supply a number of digits
你可以用Math.Floor做到这一点。但是,您需要乘以 * 100 并除以,因为您无法提供多个数字
Dim theNumber as Double
theNumber = 2.556
Dim theRounded = Math.Sign(theNumber) * Math.Floor(Math.Abs(theNumber) * 100) / 100.0
回答by Saul Dolgin
Another way to do it that doesn't rely on using the String type:
另一种不依赖于使用 String 类型的方法:
Dim numberToRound As Decimal
Dim truncatedResult As Decimal
numberToRound = 2.556
truncatedResult = (Fix(numberToRound*100))/100
回答by WyrdestGeek
The Math.Floor( ) answer is good. I'm not sure exactly which VB environments Fix( ) is defined in. As Justin points out, Math.Floor( ) won't work with negative numbers. You'd have to take the absolute value, then multiply by the SGN( ) of the number. I don't know the exact name of the function that you'd use to get the SiGN (not sin() ) of the number.
Math.Floor() 的答案很好。我不确定Fix() 是在哪个VB 环境中定义的。正如Justin 指出的那样,Math.Floor() 不适用于负数。您必须取绝对值,然后乘以数字的 SGN( )。我不知道您用来获取数字的 SiGN(不是 sin() )的函数的确切名称。
In pseudo-code, taking negative values into account, the result would looks like:
在伪代码中,考虑到负值,结果如下所示:
result = sgn( num ) * floor( abs( num * RoundToDig ) ) / RoundToDig
-- Furry cows moo and decompress.
-- 毛茸茸的奶牛哞哞并减压。
回答by ad48
To round down
四舍五入
Math.Floor(number)
To trim characters
修剪字符
number.Substring(0,1)
You can convert it to string.
您可以将其转换为字符串。
回答by Oncure1
Dim Input As Decimal
Dim Output As Decimal
Input = 2.556
Output = Input - (Input Mod 0.01)
This will work with both positive and negative numbers
这将适用于正数和负数