Domanda

I have the following variable. I need to find how many numbers are before the decimal point and after the decimal point.

    Dim x As Long = 123.456

I have tried converting this into a string

    Dim xstr As String = x.ToString(x)
    Dim searchChar As String = "."

How can I display the number of characters before the decimal point. i.e. '3'

and also, the number of characters after the decimal point. '3'.

È stato utile?

Soluzione

You can call String.Split, like this:

Dim x As Double = 123.456
Dim xstr As String = x.ToString()
Dim searchChar As String = "."
Dim parts() As String = xstr.Split({searchChar}, StringSplitOptions.None)
Dim firstLength As Integer = parts(0).Length
Dim secondLength As Integer = parts(1).Length

Altri suggerimenti

Another possible solution, based on String.Substring():

Dim x As Double = 123.456

Dim xstr As String = x.ToString(NumberFormatInfo.InvariantInfo)

Dim beforeDecimalSeparator As Integer = xstr.Length

Dim afterDecimalSeparator As Integer = 0

Dim decimalSeparatorPosition As Integer = xstr.IndexOf("."c)

If decimalSeparatorPosition > -1 Then

    beforeDecimalSeparator = xstr.Substring(0, decimalSeparatorPosition).Length

    afterDecimalSeparator = xstr.Substring(decimalSeparatorPosition + 1).Length

End If

in your way:

xstr.Substring(xstr.IndexOf("."c) + 1)

But you do not need convert to String.

Dim y = x Mod 1

You can also use IndexOf to solve this issue.

Dim x As Double = 123.456
Dim xstr As String = x.ToString()
Dim mIndex As Integer = xstr.IndexOf(".")
Dim firstLength  As Integer = mIndex;
Dim secondLength As Integer = (xstr.Length - mIndex) -1
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top