views:

467

answers:

3

Hi

I have a vb application that need to round a number down e.g. 2.556 would become 2.55 and not 2.26

I can do this using a function to strip off the characters more that 2 right from the decimal point using this:

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)

Does any one know of a better function to do this?

+6  A: 

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

Dim theNumber as Double
theNumber = 2.556
Dim theRounded = Math.Sign(theNumber) * Math.Floor(Math.Abs(theNumber) * 100) / 100.0
Reed Copsey
This won't work if the number is negative.
Justin
Sometimes it's beneficial to store your numbers as integers, or fixed-point (if you don't need the full range of floating-point), performing calculations on the fixed-point numbers and then adjust them when displaying to the user.
David Smith
@Justin: Good point - I edited to account for negative numbers, as well as positive
Reed Copsey
Since this is VB, just use a Currency datatype.
Robert L
+3  A: 

Another way to do it that doesn't rely on using the String type:

Dim numberToRound As Decimal
Dim truncatedResult As Decimal
numberToRound = 2.556
truncatedResult = (Fix(numberToRound*100))/100
Saul Dolgin
Using Fix() will be slightly faster than using Floor().
Justin
Do you anything that supports that statement?
Reed Copsey
@Justin: Fix is actually slower than Math.Floor - it does a check, then calls Math.Floor internally. Run reflector on Microsoft.VisualBasic.dll for details.
Reed Copsey
Whoops I said it backwards. Your comment was my rationale.
Justin
+2  A: 

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.

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.

WyrdestGeek
I am used to the Fix() function from VB6, but it is available in VB.NET as well - http://msdn.microsoft.com/en-us/library/microsoft.visualbasic.conversion.fix.aspx
Saul Dolgin
@WyrdestGeek: The function is Math.Sign. @Saul: Fix calls Math.Floor internally.
Reed Copsey
What is this business about decompressing bovines?
Saul Dolgin