Imports System
Imports System.Globalization ' CultureInfo
Module Program
''' <summary>
''' Returns the Nth digit after the decimal point.
''' </summary>
''' <param name="value">
''' The floating-point number to inspect.
''' </param>
''' <param name="position">
''' The digit position after the decimal point (1-based).
''' </param>
''' <returns>
''' The requested digit (0-9), or 0 if the digit does not exist.
''' </returns>
Public Function GetNthDecimalDigit(ByVal value As Decimal, ByVal position As Integer) As Integer
If position < 1 Then
Throw New ArgumentOutOfRangeException(
NameOf(position),
"Position must be greater than zero."
)
End If
' Convert to positive value.
value = Math.Abs(value)
' Convert the number to a string.
' F18 = fixed-point with 18 digits after the decimal point.
Dim numberString As String =
value.ToString("F28", CultureInfo.InvariantCulture)
' Find the decimal point.
Dim decimalPos As Integer =
numberString.IndexOf("."c)
If decimalPos = -1 Then
Return 0
End If
' Calculate the position of the requested digit.
Dim digitIndex As Integer =
decimalPos + position
If digitIndex >= numberString.Length Then
Return 0
End If
Return Integer.Parse(numberString(digitIndex).ToString())
End Function
Sub Main()
' For many business and financial applications, Decimal is preferred over
' Double because it stores decimal values more accurately
Dim number As Decimal = 123.456789123456789D
Console.WriteLine($"Number: {number}")
Console.WriteLine()
For i As Integer = 1 To 6
Console.WriteLine(
$"{i} digit after decimal = {GetNthDecimalDigit(number, i)}")
Next
Console.WriteLine()
Console.WriteLine("Additional Examples")
Console.WriteLine("-------------------")
Console.WriteLine(
$"123.456789, position 4 -> {GetNthDecimalDigit(123.456789, 4)}")
Console.WriteLine(
$"-98.7654, position 2 -> {GetNthDecimalDigit(-98.7654, 2)}")
Console.WriteLine(
$"1.2, position 5 -> {GetNthDecimalDigit(1.2, 5)}")
End Sub
End Module
' run:
'
' Number: 123.456789123456789
'
' 1 digit after decimal = 4
' 2 digit after decimal = 5
' 3 digit after decimal = 6
' 4 digit after decimal = 7
' 5 digit after decimal = 8
' 6 digit after decimal = 9
'
' Additional Examples
' -------------------
' 123.456789, position 4 -> 7
' -98.7654, position 2 -> 6
' 1.2, position 5 -> 0
'