Rounding a Number in Visual Basic

I have a Visual Basic application that needs to round a number down, for example 2.556 becomes 2.55, not 2.26.

I can do this using a function to disable characters greater than 2 to the right of 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 feature for this?

+7
math rounding
source share
5 answers

You can do this with Math.Floor . However, you need to multiply * 100 and divide, since you cannot specify multiple digits

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

Another way to do this, without relying on the use of the String type:

 Dim numberToRound As Decimal Dim truncatedResult As Decimal numberToRound = 2.556 truncatedResult = (Fix(numberToRound*100))/100 
+3
source share

The answer of Math.Floor () is good. I am not sure which VB Fix () environments are defined. As Justin points out, Math.Floor () will not work with negative numbers. You will need to take an absolute value and then multiply the numbers by SGN (). I do not know the exact name of the function that you would use to get SiGN (not sin ()) numbers.

In pseudocode that takes into account negative values, the result will look like this:

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

- Fluffy cow mu and unpacked.

+2
source share

To round

 Math.Floor(number) 

To crop characters

 number.Substring(0,1) 

You can convert it to a string.

+1
source share
 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.

0
source share

All Articles