Imports System
Imports System.Globalization ' CultureInfo
Imports System.Text
Module ReplaceFloatDigitProgram
' Function to replace a digit at a given position in a floating-point number
Function ReplaceFloatDigit(number As Double, position As Integer, newDigit As Char) As Double
' Validate that newDigit is indeed a digit
If newDigit < "0"c OrElse newDigit > "9"c Then
Throw New ArgumentException("Replacement must be a digit (0-9).")
End If
' Convert number to string with fixed precision
Dim strNum As String = number.ToString("F10", CultureInfo.InvariantCulture)
' Validate position
If position < 0 OrElse position >= strNum.Length Then
Throw New ArgumentOutOfRangeException(NameOf(position), "Position is out of range for the number string.")
End If
' Ensure position points to a digit
If strNum(position) = "."c OrElse strNum(position) = "-"c Then
Throw New ArgumentException("Position points to a non-digit character.")
End If
' Replace digit
Dim sb As New StringBuilder(strNum)
sb(position) = newDigit
' Convert back to double
Return Double.Parse(sb.ToString(), CultureInfo.InvariantCulture)
End Function
Sub Main()
Try
Dim num As Double = 89710.291
Dim pos As Integer = 2 ' 0-based index
Dim newDigit As Char = "8"c
Dim result As Double = ReplaceFloatDigit(num, pos, newDigit)
Console.WriteLine("Modified number: {0:F3}", result)
Catch ex As Exception
Console.Error.WriteLine("Error: " & ex.Message)
End Try
End Sub
End Module
' run:
'
' Modified number: 89810.291
'