Home > database >  Truncate decimals in string VB
Truncate decimals in string VB

Time:07-22

I need only 4 decimals in a string.

Dim testString As String = "78.568134"

I want to truncate testString to = "78.5681"

CodePudding user response:

Try the following methods based on your needs and modifications;

Try method 1)

Function TrimDigits(val As Double, Optional numdig As Integer = 2) As Double
Try
    Return Fix(val * 10 ^ numdig) / 10 ^ numdig
Catch ex As Exception
    Return 0
End Try
End Function

Try method 2)

truncatedNumber = Fix ( originalNumber * 100 ) / 100 'Truncate to 2 decimals.
truncatedNumber = Fix ( originalNumber * 1000 ) / 1000 'Truncate to 3 decimals.
truncatedNumber = Fix ( originalNumber * 10000 ) / 10000 'Truncate to 4 decimals.

Aside note Fix() returns the integer portion of a number.

Example 01: Truncate 3.1415 to 2 decimals.

3.1415 x 100 equals 314.15 Fix(314.15) returns 314 314 / 100 equals 3.14 Example 02: Truncate 3.1415 to 3 decimals.

3.1415 x 1000 equals 3141.5 Fix(3141.5) returns 3141 3141 / 1000 equals 3.141

Int does not truncate negative numbers correctly. Int converts -8.4 to -9, and Fix converts -8.4 to -8. So Fix is the way to go

CodePudding user response:

Code to find the index of the decimal point and truncate the string if there are more than 4 characters after it.

Dim stringLen As Integer = testString.Length
Dim decimalOffset As Integer = testString.IndexOf(".", 0)

If decimalOffset >= 0 Then
    If stringLen > decimalOffset   5 Then testString = testString.SubString(0, decimalOffset   5)
End If

This is if you are only working with Strings. If you are working with Doubles there are other ways to do this.

  • Related