문제

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'.

도움이 되었습니까?

해결책

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

다른 팁

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
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top