I have the string value in the following format: "210.0n" and I need to compare it with the value "2.1e-07". Direct comparison, of course, will fail.
Is there any way how to convert such strings like this "210.0n", "0.7m", "10.0K" (with units metrics) to the normal float values? Maybe dedicated Go module is available? I can't find it.
You can write this in a simple switch case yourself. There is no need for a library.
var str = "100k"
mFloat, err := strconv.ParseFloat(str[:len(str)-1], 64)
if err != nil{
//handle error
}
switch string(str[len(str)-1]){
case "k":
mFloat = mFloat * 1000
fmt.Printf("%e", )
case "m":
mFloat = mFloat * 1000000
fmt.Printf("%e", mFloat * 1000000)
// etc ....
}
return mFloat
Different suffixes: https://www.mathsisfun.com/metric-numbers.html
If this answer will help somebody then I have found this package on Github github.com/dustin/go-humanize which contains the necessary code to translate such kind of strings like "240n" "1p" and etc to the float. It contains even more possibilities for data converting. Hope it will help some newbies who work with floats in Go.