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

2 Answers

0 votes
Imports System

'
' FirstDigitAfterDecimal:
' -----------------------
' Extracts the first digit after the decimal point from a floating‑point number.
'
' Method:
' 1. Convert the number to a string.
' 2. Locate the decimal point.
' 3. Take the character immediately after it.
' 4. Convert that character to an integer.
'
' This uses familiar built‑in string functions and keeps the logic clear.
'
Public Class Program
    Public Shared Function FirstDigitAfterDecimal(value As Single) As Integer
		Dim s As String = value.ToString()
		Dim dotIndex As Integer = s.IndexOf("."c)
		
		Return Integer.Parse(s.Substring(dotIndex + 1, 1))
	End Function
	
	Public Shared Sub Main()
        Dim f As Single = 7312.891

        Dim digit As Integer = FirstDigitAfterDecimal(f)

        Console.Write(digit)
    End Sub
End Class


' run:
'
' 8
'

 



answered Aug 30, 2019 by avibootz
edited Sep 16 by avibootz
0 votes
Imports System

Public Class Test
    ' FirstDigitAfterDecimal:
    ' -----------------------
    ' Extracts the first digit after the decimal point from a floating-point number.
    '
    ' Method:
    ' 1. Take the absolute value to handle negative numbers consistently.
    ' 2. Multiply by 10 to shift the first decimal digit into the integer part.
    ' 3. Use Math.Floor to avoid rounding issues.
    ' 4. Apply Mod 10 to isolate the first digit.
    ' 5. Convert the result to Integer with CInt.
    '
    Public Shared Function FirstDigitAfterDecimal(value As Single) As Integer
        Return CInt(Math.Floor(Math.Abs(value) * 10) Mod 10)
    End Function

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

        Dim digit As Integer = FirstDigitAfterDecimal(f)

        Console.Write(digit)
    End Sub
End Class


' run:
'
' 8
'

 



answered Aug 31, 2019 by avibootz
edited Sep 16 by avibootz

Related questions

...