How to replace all occurrences of a specific digit in a floating-point number with Go

1 Answer

0 votes
package main

import (
    "fmt"
    "strconv"
    "strings"
)

func replaceAllDigits(num float64, oldDigit, newDigit rune) float64 {
    // Format the number to a string with 3 decimal places
    strNum := fmt.Sprintf("%.3f", num)

    // Replace all occurrences of oldDigit with newDigit
    modifiedStr := strings.Map(func(r rune) rune {
        if r == oldDigit {
            return newDigit
        }
        return r
    }, strNum)

    // Convert the modified string back to float64
    result, err := strconv.ParseFloat(modifiedStr, 64)
    if err != nil {
        return 0.0 // fallback in case of conversion error
    }
    
    return result
}

func main() {
    fmt.Printf("%.3f\n", replaceAllDigits(82420.291, '2', '6'))
    fmt.Printf("%.3f\n", replaceAllDigits(111.11, '1', '5'))
}



/*
run:

86460.691
555.550

*/

 



answered 15 hours ago by avibootz

Related questions

...