2009-08-04 59 views
7

我有一个Visual Basic应用程序需要向下舍入数字,例如2.556会变成2.55而不是2.26。在Visual Basic中舍入数字

我可以用一个函数来使用这个小数点去掉字符超过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) 

是否有更好的功能来做到这一点?

回答

10

你可以用Math.Floor来做到这一点。但是,你需要乘* 100和除法,因为你不能提供一个位数

Dim theNumber as Double 
theNumber = 2.556 
Dim theRounded = Math.Sign(theNumber) * Math.Floor(Math.Abs(theNumber) * 100)/100.0 
+0

如果数字为负则无法使用此工作。 – Justin 2009-08-04 16:33:18

+0

有时将您的数字存储为整数或定点(如果您不需要全部浮点数),对定点数执行计算并在显示给用户时对其进行调整是有益的。 – 2009-08-04 16:45:32

+0

@Justin:好点 - 我编辑为负数,以及积极 – 2009-08-04 16:47:21

3

另一种方式来做到这一点是不依赖于使用String类型:

Dim numberToRound As Decimal 
Dim truncatedResult As Decimal 
numberToRound = 2.556 
truncatedResult = (Fix(numberToRound*100))/100 
2

Math.Floor()答案很好。我不确定究竟在哪个VB环境中定义了Fix()。正如Justin指出的,Math.Floor()不适用于负数。你必须取绝对值,然后乘以数字的SGN()。我不知道你用来获取SiGN(不是sin())的函数的确切名称。

在伪代码,以负值进去,结果会是这样的:

result = sgn(num) * floor(abs(num * RoundToDig))/RoundToDig 

- 毛茸茸的牛哞和解压。

1

向下舍

Math.Floor(number) 

要修剪字符

number.Substring(0,1) 

你可以将其转换为字符串。

0
Dim Input As Decimal 
Dim Output As Decimal 
Input = 2.556 
Output = Input - (Input Mod 0.01) 

这将二者正数和负数