How to replace all occurrences of a specific digit in a floating-point number with VB.NET

1 Answer

0 votes
Imports System
Imports System.Globalization

Module Program
    Function ReplaceAllDigits(num As Double, oldDigit As Char, newDigit As Char) As Double
        ' Convert number to string with 3 decimal places using invariant culture
        Dim strNum As String = num.ToString("F3", CultureInfo.InvariantCulture)

        ' Replace all occurrences of oldDigit with newDigit
        Dim modifiedStr As String = strNum.Replace(oldDigit, newDigit)

        ' Convert the modified string back to double
        Return Double.Parse(modifiedStr, CultureInfo.InvariantCulture)
    End Function

    Sub Main()
        Console.WriteLine(ReplaceAllDigits(82420.291, "2"c, "7"c).ToString("F3", CultureInfo.InvariantCulture))
        Console.WriteLine(ReplaceAllDigits(111.11, "1"c, "5"c).ToString("F3", CultureInfo.InvariantCulture))
    End Sub
End Module



' run:
'
' 87470.791
' 555.550
'

 



answered 18 hours ago by avibootz

Related questions

...