How to get the first digit of a float number in VB.NET

4 Answers

0 votes
Imports System

Public Class Test

    Public Shared Function GetFirstDigit(f As Single) As Integer
        Dim s As String = f.ToString()
		
        Return Integer.Parse(s.Substring(0, 1))
    End Function

    Public Shared Sub Main()
        Dim f As Single = 872.1459F

        Console.Write(GetFirstDigit(f))   
    End Sub

End Class



' run:
'
' 8
' 

 



answered Aug 29, 2019 by avibootz
edited Sep 15 by avibootz
0 votes
Imports System

Public Class Test

	Public Shared Function GetFirstDigit(f As Single) As Integer
		Dim str As String = Math.Abs(f).ToString()
		
		Return Integer.Parse(str(0).ToString())
	End Function

    Public Shared Sub Main()
        Dim f As Single = 972.1459F

        Console.Write(GetFirstDigit(f))   ' prints 9
    End Sub

End Class


' run:
'
' 9
' 

 



answered Aug 29, 2019 by avibootz
edited Sep 15 by avibootz
0 votes
Imports System

Public Class Test

	Public Shared Function GetFirstDigit(f As Single) As Integer
		Dim int_part As Integer = CInt(Math.Floor(f))
		Dim total_digits_minus_one As Integer = CInt(Math.Floor(Math.Log10(int_part)))
		Dim first_digit As Integer = CInt(Math.Truncate(int_part / Math.Pow(10, total_digits_minus_one)))
		
		Return first_digit
	End Function

    Public Shared Sub Main()
        Dim f As Single = 972.1459F

        Console.Write(GetFirstDigit(f))   ' prints 9
    End Sub

End Class


' run:
'
' 9
' 

 



answered Sep 15 by avibootz
0 votes
Imports System

Public Class Test

	Public Shared Function GetFirstDigit(f As Single) As Integer
		Dim int_part As Integer = CInt(Math.Floor(f))
		Dim total_digits_minus_one As Integer = CInt(Math.Floor(Math.Log10(int_part)))
		Dim first_digit As Integer = CInt(Microsoft.VisualBasic.Conversion.Fix(int_part / Math.Pow(10, total_digits_minus_one)))
		
		Return first_digit
	End Function

    Public Shared Sub Main()
        Dim f As Single = 972.1459F

        Console.Write(GetFirstDigit(f))   ' prints 9
    End Sub

End Class


' run:
'
' 9
' 

 



answered Sep 15 by avibootz
...