The problem is that you try to parse "x.x\n", e.g: 1.8\n. And this returns an error: strconv.ParseFloat: parsing "1.8\n": invalid syntax. You can do a strings.TrimSpace function or to convert feet[:len(feet)-1] to delete \n character

With strings.TrimSpace() (you need to import strings package):

feetFloat, _ := strconv.ParseFloat(strings.TrimSpace(feet), 64)

Wtih feet[:len(feet)-1]:

feetFloat, _ := strconv.ParseFloat(feet[:len(feet)-1], 64)

Output in both cases:

10.8 feet converted to meters give you 3.2918400000000005 meters
Answer from Toni Villena on Stack Overflow
🌐
Educative
educative.io › answers › how-to-use-the-strconvparsefloat-function-in-golang
How to use the strconv.ParseFloat() function in Golang
The ParseFloat() function is a strconv package inbuilt function that converts strings to a floating-point number with the precision defined by the bitSize. The value of bitSize must be 32 or 64.
Discussions

proposal: strconv: add ParseFloatPrefix
The strconv.ParseFloat function parses a floating-point value from a string, but it requires that the floating-point value is the entire string, otherwise it returns an error. In many types of pars... More on github.com
🌐 github.com
10
June 12, 2022
go - Convert string to float32? - Stack Overflow
float has the type float32, but strconv.ParseFloat returns float64. More on stackoverflow.com
🌐 stackoverflow.com
strconv.ParseFloat() faster altrernatives
You seem to know what you're doing in terms of parsing and profiling. Maybe optimize the ParseFloat implementation . You say you're only accepting a fixed format and I assume a fixed precision, and in the parsing process you're presumably already checking the syntax so you only need the conversion part. You can duplicate ParseFloat and cut the duplicate steps and have something more granular to profile and optimize. More on reddit.com
🌐 r/golang
9
2
October 4, 2022
parsing - Golang ParseFloat not accurate in example - Stack Overflow
Is ParseFloat() what I should be using in this scenario? If not, I'd love to hear a brief explanation on this, as I'm still a programmer in learning. ... I don't think you should use floats for currency values. ... So, for this example - the amount that the API is returning is unfortunately a string. I've done a quick work around (just to have the ability to check if the actual amount is the same as the string amount). Example is here: play.golang... More on stackoverflow.com
🌐 stackoverflow.com
🌐
ZetCode
zetcode.com › golang › strconv-parsefloat
Using strconv.ParseFloat in Go
April 20, 2025 - Learn how to parse floating-point numbers from strings using strconv.ParseFloat in Go. Includes practical examples and error handling.
🌐
YourBasic
yourbasic.org › golang › convert-string-to-float
Convert between float and string · YourBasic Go
yourbasic.org/golang · ... 9234603 48610454326648 2133936 0726024914127 3724587 00660631558 817488 152092096 · Use the strconv.ParseFloat function to parse a string as a floating-point number with the precision specified ...
🌐
Reintech
reintech.io › blog › introduction-to-gos-strconv-package-string-conversions
An Introduction to Go's `strconv` Package: String Conversions | Reintech media
January 26, 2026 - The strconv.ParseFloat() function in Go is used to convert a string to a floating-point number. This function takes two arguments: the string to be converted and the number of bits the floating-point number should occupy (32 or 64).
🌐
Educative
educative.io › answers › how-to-convert-a-string-to-a-float-in-golang
How to convert a string to a float in Golang
A string can be converted to a float in Golang using the ParseFloat function within the strconv package.
🌐
TutorialsPoint
tutorialspoint.com › how-to-convert-string-to-float-type-in-golang
How to Convert string to float type in Golang?
May 5, 2023 - In Go, we can convert a string to a float type using the strconv package. The strconv package provides the ParseFloat function to convert a string to a float type. This function takes three arguments - the string to be converted, the bit size of the float type, and the precision of the float type.
🌐
Go Packages
pkg.go.dev › strconv
strconv package - strconv - Go Packages
ParseFloat accepts decimal and hexadecimal floating-point numbers as defined by the Go syntax for floating-point literals. If s is well-formed and near a valid floating-point number, ParseFloat returns the nearest floating-point number rounded using IEEE754 unbiased rounding.
Find elsewhere
🌐
GitHub
github.com › golang › go › issues › 53340
proposal: strconv: add ParseFloatPrefix · Issue #53340 · golang/go
June 12, 2022 - The strconv.ParseFloat function parses a floating-point value from a string, but it requires that the floating-point value is the entire string, otherwise it returns an error. In many types of parsing you want to know if a string starts ...
Author   benhoyt
🌐
IncludeHelp
includehelp.com › golang › strconv-parsefloat-function-with-examples.aspx
Golang strconv.ParseFloat() Function with Examples
September 10, 2021 - The return type of the ParseFloat() function is (float64, error), it returns the floating-point number converted from the given string. // Golang program to demonstrate the // example of strconv.ParseFloat() Function package main import ( "fmt" "strconv" ) func main() { fmt.Println(strconv.ParseFloat("123.50", 32)) fmt.Println(strconv.ParseFloat("123.50", 64)) fmt.Println(strconv.ParseFloat("-123456789.501234", 32)) fmt.Println(strconv.ParseFloat("-123456789.501234", 64)) fmt.Println() fmt.Println(strconv.ParseFloat("NaN", 32)) fmt.Println(strconv.ParseFloat("Inf", 32)) fmt.Println(strconv.ParseFloat("-Inf", 32)) }
🌐
Cloudhadoop
cloudhadoop.com › home
Golang Example - strconv ParseFloat function guide
December 31, 2023 - package main import ( "fmt" "reflect" "strconv" ) func main() { floatNumb, err: = strconv.ParseFloat("123.23", 32) fmt.Println(floatNumb) fmt.Println(reflect.TypeOf(floatNumb)) fmt.Println(err) float32Value: = float32(floatNumb) // Convert to float 32 fmt.Println(float32Value) fmt.Println(reflect.TypeOf(float32Value)) } Output: 123.2300033569336 float64 <nil> 123.23 float32 · #Golang · #Golang-examples · Categories · Javascript (6) Angular (84) Dart (116) Golang (25) Java (69) Primeng (14) Python (44) Typescript (69) Vuejs (18) Blockchain (1) Reactjs (63) Git (5) Nodejs (64) Node (1) Swift (48) Tags ·
🌐
GeeksforGeeks
geeksforgeeks.org › how-to-convert-string-to-float-type-in-golang
How to Convert string to float type in Golang? - GeeksforGeeks
May 19, 2020 - If a1 or a2 is well-formed and near a valid floating-point number, ParseFloat returns the nearest floating-point number rounded using IEEE754 unbiased rounding which is parsing a hexadecimal floating-point value only rounds when there are more bits in the hexadecimal representation than will fit in the mantissa. ... // Golang program to Convert // string to float type package main import ( "fmt" "strconv" ) func main() { // defining a string a1 a1 := "-2.514" // converting the string a1 // into float and storing it // in b1 using ParseFloat b1, _ := strconv.ParseFloat(a1, 8) // printing the float b1 fmt.Println(b1) a2 := "-2.514" b2, _ := strconv.ParseFloat(a2, 32) fmt.Println(b2) fmt.Println(b1 + b2) } Output:
🌐
GitHub
gist.github.com › yyscamper › 5657c360fadd6701580f3c0bcca9f63a
An advance ParseFloat for golang, support scientific notation, comma separated number · GitHub
December 13, 2020 - An advance ParseFloat for golang, support scientific notation, comma separated number - parseFloat.go
🌐
Reddit
reddit.com › r/golang › strconv.parsefloat() faster altrernatives
r/golang on Reddit: strconv.ParseFloat() faster altrernatives
October 4, 2022 -

I am parsing huge json files with my own parser where all values are float, which I use in math calculations further on. pprof profiling says 60% of the time is used by the strconv.ParseFloat(). I looked into the code of the ParseFloat() and it's pretty comprehensive, not much clue on my side. Also I checked github and goolged it, but no results suggesting anything else. I believe the strconv.ParseFloat() is probably pretty optimized but nevertheless, I just wonder if anyone has some faster alternative suggestions to the strconv.ParseFloat()? Thanks..

🌐
TutorialKart
tutorialkart.com › golang-tutorial › golang-convert-string-to-float
How to convert String to Float in Go Language?
July 1, 2021 - package main import ( "fmt" "strconv" ) func main() { var str = "14.2356" result, err := strconv.ParseFloat(str, 32) if err == nil { fmt.Println("The float value is :", result) } else { fmt.Println("There is an error converting string to float.") } }
Top answer
1 of 3
1

Go uses IEEE-754 binary floating-point numbers. Floating-point numbers are imprecise. Don't use them for financial transactions. Use integers.

For example,

package main

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

func parseCents(s string) (int64, error) {
    n := strings.SplitN(s, ".", 3)
    if len(n) != 2 || len(n[1]) != 2 {
        err := fmt.Errorf("format error: %s", s)
        return 0, err
    }
    d, err := strconv.ParseInt(n[0], 10, 56)
    if err != nil {
        return 0, err
    }
    c, err := strconv.ParseUint(n[1], 10, 8)
    if err != nil {
        return 0, err
    }
    if d < 0 {
        c = -c
    }
    return d*100 + int64(c), nil
}

func main() {
    s := "79.35"
    fmt.Println(parseCents(s))
    s = "149.20"
    fmt.Println(parseCents(s))
    s = "-149.20"
    fmt.Println(parseCents(s))
    s = "149.2"
    fmt.Println(parseCents(s))
}

Playground: https://play.golang.org/p/mGuO51QWyIv

Output:

7935 <nil>
14920 <nil>
-14920 <nil>
0 format error: 149.2
2 of 3
0

Based on @peterSO's answer, with some bugfix and enhancement:

https://play.golang.org/p/YcRLeEJ7lTA

package main

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

func parseCents(s string) (int64, error) {
    var ds string
    var cs string

    n := strings.SplitN(s, ".", 3)
    switch len(n) {
    case 1:
        ds = n[0]
        cs = "0"
    case 2:
        ds = n[0]
        switch len(n[1]) {
        case 1:
            cs = n[1] + "0"
        case 2:
            cs = n[1]
        default:
            return 0, fmt.Errorf("invalid format:%s", s)
        }
    default:
        return 0, fmt.Errorf("invalid format:%s", s)
    }

    d, err := strconv.ParseInt(ds, 10, 0)
    if err != nil {
        return 0, err
    }

    c, err := strconv.ParseUint(cs, 10, 0)
    if err != nil {
        return 0, err
    }

    cents := d * 100

    if strings.HasPrefix(s, "-") {
        cents -= int64(c)
    } else {
        cents += int64(c)
    }

    return cents, nil
}

func main() {
    examples := map[string]int64{
        "79.35": 7935,
        "149.20": 14920,
        "-149.20": -14920,
        "149.2": 14920,
        "-0.12": -12,
        "12": 1200,
        "1.234": 0,
        "1.2.34": 0,
    }

    for s, v := range examples {
        cents, err := parseCents(s)
        fmt.Println(cents, cents == v, err)
    }
}
🌐
Educative
educative.io › answers › how-to-use-the-strconvparseint-function-in-golang
How to use the strconv.ParseInt() function in Golang
// ParseFloat() converts variable str to a integer number · // with the specified base and bitSize · // diplays result · fmt.Println(strconv.ParseInt(str, 16, 32)) // throw out of range error · fmt.Println(strconv.ParseInt(str, 16, 64)) ...
Top answer
1 of 2
8

Your best bet is the use the standard library's strconv. You can make your own wrappers and locale stuff. Eventually I'd add more error checking and turn this into it's own package, but here is an idea. If you haven't found a package yet there is a good chance you will have to write your own. For a more general solution, you'd have to think about every possible input.. normalize that per locale and enforce those rules when others are using your tools... That would be a more complex solution given the number of if statements and pieces of logic.. The good part is that you know the type of input strconv.ParseFloat expects.. So all you really have to do is take the user input and transform it to the programmatic standard http://floating-point-gui.de/formats/fp/. Given numbers are mostly universal, with the exception of commas and decimal points, there shouldn't be many use cases. You might even be able to generalize further and say there are two main formats.. https://www.quora.com/Why-do-some-countries-use-a-period-and-others-use-a-comma-to-separate-large-numbers, which is largely broken down to Europe et al and British/American, where German uses the standard almost all of Europe does. Under that assumption there isn't really much to do as the use cases comes down to 2.

package main

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

func normalizeGerman(old string) string {
    s := strings.Replace(old, ",", ".", -1)
    return strings.Replace(s, ".", "", 1)
}
func normalizeAmerican(old string) string {
    return strings.Replace(old, ",", "", -1)
}

var locale map[string]func(string) string

func init() {
    locale = make(map[string]func(string) string)
    locale["DE-DE"] = normalizeGerman
    locale["US"] = normalizeAmerican
}

func main() {
    var f, f2 float64
    var err error
    // german
    if val, ok := locale["DE-DE"]; ok {
        f, err = strconv.ParseFloat(val("1.234,87"), 64)
        if err != nil {
            log.Fatal("german fail", err)
        }
    }
    //american
    if val, ok := locale["US"]; ok {
        f2, err = strconv.ParseFloat(val("1,234.87"), 64)
        if err != nil {
            log.Fatal("american fail", err)
        }
    }

    fmt.Println(f, f2)

}
2 of 2
2

/x/text unfortunately doesn't (publicly) expose everything you need for this, but I was able to leverage it to build something that works pretty well and integrates with /x/text for picking locale

// Locale-aware number parsing with lxstrconv
//
// Docs: https://godoc.org/tawesoft.co.uk/go/lxstrconv

package main

import (
    "fmt"
    "golang.org/x/text/language"
    "tawesoft.co.uk/go/lxstrconv"
)

func checked(f float64, e error) float64 {
    if e != nil {
        panic(e)
    }
    return f
}

func main() {
    dutch   := lxstrconv.NewDecimalFormat(language.Dutch)
    british := lxstrconv.NewDecimalFormat(language.BritishEnglish)
    arabic  := lxstrconv.NewDecimalFormat(language.Arabic)

    fmt.Printf("%f\n", checked(british.ParseFloat("1,234.56")))
    fmt.Printf("%f\n", checked(dutch.ParseFloat("1.234,56")))
    fmt.Printf("%f\n", checked(arabic.ParseFloat("١٬٢٣٤٫٥٦")))
}
🌐
YourBasic
yourbasic.org › golang › round-float-2-decimal-places
Round float to 2 decimal places · YourBasic Go
Use strconv.ParseFloat to parse a floating point number from a string, and fmt.Sprintf to format a float as a string.