Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rounding a number down in Visual Basic

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.

I can do this using a function to strip off the characters more than 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)

Is there a better function to do this?

like image 649
Paul Avatar asked Aug 04 '09 16:08

Paul


People also ask

How do you round numbers in Visual Basic?

The basic function for rounding up is Math. Ceiling(d), but the asker specifically wanted to round up after the second decimal place. This would be Math. Ceiling(d * 100) / 100.

Does round () round Down?

The round() function rounds a number to the nearest whole number. The math. ceil() method rounds a number up to the nearest whole number while the math. floor() method rounds a number down to the nearest whole number.

Does round () round up or down?

Round rounds up if the next digit is 5 or higher. Otherwise, this function rounds down. RoundDown always rounds down to the previous lower number, towards zero. RoundUp always rounds up to the next higher number, away from zero.


2 Answers

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
like image 198
Reed Copsey Avatar answered Sep 22 '22 18:09

Reed Copsey


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
like image 45
Saul Dolgin Avatar answered Sep 21 '22 18:09

Saul Dolgin