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
🌐
YourBasic
yourbasic.org › golang › convert-string-to-float
Convert between float and string · YourBasic Go
Use the strconv.ParseFloat function to parse a string as a floating-point number with the precision specified by bitSize: 32 for float32, or 64 for float64.
Discussions

go - How to convert float to string - Stack Overflow
I read a float from a file and will have to convert it to string. My problem here is that I am unsure of how many digits will be there after the decimal. I need to take the float exactly and conver... More on stackoverflow.com
🌐 stackoverflow.com
strconv: inaccurate string to float64 conversion ParseFloat
$ go env GO111MODULE="" GOARCH="amd64" ... -O2" CGO_FFLAGS="-g -O2" CGO_LDFLAGS="-g -O2" PKG_CONFIG="pkg-config" Here's the code: https://play.golang.org/p/izkaZ-XBog5 · I'm converting string "1090544144181609348835077142190" to float64 with strconv.ParseFloat("109054414... More on github.com
🌐 github.com
20
January 20, 2020
go - How to convert []string to []float64 in Golang? - Stack Overflow
I really don't like that you have changed the meaning of my code with your edit :/ 2015-01-10T12:50:48.887Z+00:00 ... Please undo my edit if you do not like it. It's okay. 2015-01-10T13:05:33.587Z+00:00 ... Thank you very much. 1. for iterates over a slice is really simple yet useful. I guess this is the counterpart of map in a functional language. 2. strconv.ParseFloat not only convert the string ... More on stackoverflow.com
🌐 stackoverflow.com
Converting a float to string
http://golang.org/pkg/strconv/#FormatFloat http://golang.org/pkg/strconv/#ParseFloat If you don't care about errors, write a small wrapper func. More on reddit.com
🌐 r/golang
5
3
November 20, 2014
🌐
Go Packages
pkg.go.dev › strconv
strconv package - strconv - Go Packages
Output: float32:3.1415927E+00 float64:3.1415926535E+00 ... AppendInt appends the string form of the integer i, as generated by FormatInt, to dst and returns the extended buffer.
🌐
Educative
educative.io › answers › how-to-convert-a-string-to-a-float-in-golang
How to convert a string to a float in Golang
If the input string is non-numeric, ... a string to a float using the ParseFloat function. ... We declared a numeric string str1 (line 11) and converted it to float using the strconv.ParseFloat() method (line 12)....
🌐
GitHub
github.com › golang › go › issues › 36657
strconv: inaccurate string to float64 conversion ParseFloat · Issue #36657 · golang/go
January 20, 2020 - The difference between string value and returned float64 value is 70531932370606 (see https://www.wolframalpha.com/input/?i=1090544144181609348835077142190-1090544144181609278303144771584) Go compiler correctly converts float64 literals to float64 constants, as you can see in Playground example https://play.golang.org/p/izkaZ-XBog5 ·
Author   g7r
🌐
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).
🌐
GeeksforGeeks
geeksforgeeks.org › go language › how-to-convert-string-to-float-type-in-golang
How to Convert string to float type in Golang? - GeeksforGeeks
May 19, 2020 - C · // 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: -2.514 -2.5139999389648438 -5.027999938964843 ·
Find elsewhere
🌐
TutorialsPoint
tutorialspoint.com › how-to-convert-string-to-float-type-in-golang
How to Convert string to float type in Golang?
May 5, 2023 - This function takes three arguments - the string to be converted, the bit size of the float type, and the precision of the float type. In this article, we will discuss how to convert a string to a float type in Go. The syntax of the ParseFloat function is as follows ? func ParseFloat(s string, ...
🌐
Educative
educative.io › answers › how-to-use-the-strconvparsefloat-function-in-golang
How to use the strconv.ParseFloat() function in Golang
func ParseFloat(s string, bitSize int) (float64, error) s: This is the string value to parse into the floating-point number. bitSize: This is to specify the precision. The value of bitSize can be 32 or 64. The ParseFloat() function returns the ...
🌐
DigitalOcean
digitalocean.com › community › tutorials › how-to-convert-data-types-in-go
How To Convert Data Types in Go | DigitalOcean
May 9, 2019 - Wrapping floats in int(), or one of its architecture-independent data types, works similarly to when you used it to convert from one integer type to another. You can add a floating-point number inside of the parentheses to convert it to an integer: var f float64 = 390.8 var i int = int(f) fmt.Printf("f = %.2f\n", f) fmt.Printf("i = %d\n", i)
🌐
Reddit
reddit.com › r/golang › converting a float to string
r/golang on Reddit: Converting a float to string
November 20, 2014 -

What is the easy way of converting a float to a string?

The strconv package seems awfully cluttered and there doesn't seem to be a function where you can simply give a float and get a string

🌐
TutorialKart
tutorialkart.com › golang-tutorial › golang-convert-string-to-float
How to convert String to Float in Go Language?
July 1, 2021 - To convert a String to a Float value in Go programming, use ParseFloat() function of strconv package.
🌐
Medium
medium.com › @kode-n-rolla › type-conversion-in-go-a-handy-cheat-sheet-for-developers-51482d4dca0c
Type Conversion in Go: A Handy Cheat Sheet for Developers | by k0de-n-Яolla | Medium
February 27, 2026 - Go’s strings are UTF-8 encoded, so they can include multibyte characters like emojis or non-Latin scripts. Converting to runes ensures accurate handling of characters, especially for indexing or slicing. Go provides built-in support for converting between numeric types like int, float64, and others.
🌐
Siongui
siongui.github.io › 2017 › 04 › 13 › go-string-float-number-type-casting
[Golang] Type Conversion between String and Floating Number
package main import ( "fmt" "strconv" ) func main() { width := "560" height := "315" // convert string to float64 w, err := strconv.ParseFloat(width, 64) if err != nil { fmt.Println(err) } h, err := strconv.ParseFloat(height, 64) if err != nil { fmt.Println(err) } // make calculation and then convert float64 to string aspectRatio := strconv.FormatFloat(h*100/w, 'f', -1, 64) + "%" fmt.Println("aspect ratio: ", aspectRatio) }
Top answer
1 of 3
30

Dave C has a good answer using reflect, and I'll compare that to type-by-type code below. First, to do what you were already doing more concisely, you can use the type switch:

    switch i := unk.(type) {
    case float64:
            return i, nil
    case float32:
            return float64(i), nil
    case int64:
            return float64(i), nil
    // ...other cases...
    default:
            return math.NaN(), errors.New("getFloat: unknown value is of incompatible type")
    }

The case float64: is like your if i, ok := unk.(float64); ok { ... }. Code for that case can access the float64 as i. Despite the lack of braces the cases act like blocks: i's type is different under each case and there is no C-style fallthrough.

Also, note large int64s (over 253) will be rounded when converted to float64, so if you're thinking of float64 as a "universal" number type, take its limitations into account.

An example of that is in the Playground at http://play.golang.org/p/EVmv2ibI_j.


Dave C mentions you can avoid writing out individual cases if you use reflect; his answer has code, and even handles named types and pointers to suitable types. He also mentions handling strings and types convertible to them. After doing a naïve test comparing options:

  • Passing the reflect version an int gets me about 13 million conversions a second; the overhead isn't noticeable unless you're converting millions of items.
  • You can write a switch to handle some common types then fall back to reflect; at least in my simple test below it goes at ~50M conversion/s and allocates less, presumably only the interface{} value without a reflect.Value.
  • A switch only over number types loses some flexibility, but can avoid allocation since the compiler can prove through escape analysis that nothing needs to remain allocated after.

That said, if you need to tune enough that you care about these differences, you should probably run your own test in the context of your code. For example, the allocations can have varying costs depending on your app's total live data size, GC settings like GOGC, and how long each collection takes, and your code might allow/prevent different optimizations (inlining, etc.) than my sample.

The code is on the Playground and below:

package main

/* To actually run the timings, you need to run this from your machine, not the Playground */

import (
    "errors"
    "fmt"
    "math"
    "reflect"
    "runtime"
    "strconv"
    "time"
)

var floatType = reflect.TypeOf(float64(0))
var stringType = reflect.TypeOf("")

func getFloat(unk interface{}) (float64, error) {
    switch i := unk.(type) {
    case float64:
        return i, nil
    case float32:
        return float64(i), nil
    case int64:
        return float64(i), nil
    case int32:
        return float64(i), nil
    case int:
        return float64(i), nil
    case uint64:
        return float64(i), nil
    case uint32:
        return float64(i), nil
    case uint:
        return float64(i), nil
    case string:
        return strconv.ParseFloat(i, 64)
    default:
        v := reflect.ValueOf(unk)
        v = reflect.Indirect(v)
        if v.Type().ConvertibleTo(floatType) {
            fv := v.Convert(floatType)
            return fv.Float(), nil
        } else if v.Type().ConvertibleTo(stringType) {
            sv := v.Convert(stringType)
            s := sv.String()
            return strconv.ParseFloat(s, 64)
        } else {
            return math.NaN(), fmt.Errorf("Can't convert %v to float64", v.Type())
        }
    }
}

func getFloatReflectOnly(unk interface{}) (float64, error) {
    v := reflect.ValueOf(unk)
    v = reflect.Indirect(v)
    if !v.Type().ConvertibleTo(floatType) {
        return math.NaN(), fmt.Errorf("cannot convert %v to float64", v.Type())
    }
    fv := v.Convert(floatType)
    return fv.Float(), nil
}

var errUnexpectedType = errors.New("Non-numeric type could not be converted to float")

func getFloatSwitchOnly(unk interface{}) (float64, error) {
    switch i := unk.(type) {
    case float64:
        return i, nil
    case float32:
        return float64(i), nil
    case int64:
        return float64(i), nil
    case int32:
        return float64(i), nil
    case int:
        return float64(i), nil
    case uint64:
        return float64(i), nil
    case uint32:
        return float64(i), nil
    case uint:
        return float64(i), nil
    default:
        return math.NaN(), errUnexpectedType
    }
}

func main() {
    var m1, m2 runtime.MemStats

    runtime.ReadMemStats(&m1)
    start := time.Now()
    for i := 0; i < 1e6; i++ {
        getFloatReflectOnly(i)
    }
    fmt.Println("Reflect-only, 1e6 runs:")
    fmt.Println("Wall time:", time.Now().Sub(start))
    runtime.ReadMemStats(&m2)
    fmt.Println("Bytes allocated:", m2.TotalAlloc-m1.TotalAlloc)

    runtime.ReadMemStats(&m1)
    start = time.Now()
    for i := 0; i < 1e6; i++ {
        getFloat(i)
    }
    fmt.Println("\nReflect-and-switch, 1e6 runs:")
    fmt.Println("Wall time:", time.Since(start))
    runtime.ReadMemStats(&m2)
    fmt.Println("Bytes allocated:", m2.TotalAlloc-m1.TotalAlloc)

    runtime.ReadMemStats(&m1)
    start = time.Now()
    for i := 0; i < 1e6; i++ {
        getFloatSwitchOnly(i)
    }
    fmt.Println("\nSwitch only, 1e6 runs:")
    fmt.Println("Wall time:", time.Since(start))
    runtime.ReadMemStats(&m2)
    fmt.Println("Bytes allocated:", m2.TotalAlloc-m1.TotalAlloc)
}

/*
Reflect-only, 1e6 runs:
Wall time: 79.853582ms
Bytes allocated: 16002696

Reflect-and-switch, 1e6 runs:
Wall time: 20.921548ms
Bytes allocated: 8000776

Switch only, 1e6 runs:
Wall time: 3.766178ms
Bytes allocated: 32
*/
2 of 3
13

You can use the reflect package for this:

import "reflect"

var floatType = reflect.TypeOf(float64(0))

func getFloat(unk interface{}) (float64, error) {
    v := reflect.ValueOf(unk)
    v = reflect.Indirect(v)
    if !v.Type().ConvertibleTo(floatType) {
        return 0, fmt.Errorf("cannot convert %v to float64", v.Type())
    }
    fv := v.Convert(floatType)
    return fv.Float(), nil
}

Runnable in the Go Playground: http://play.golang.org/p/FRM21HRq4o

🌐
Technical Feeder
technicalfeeder.com › 2023 › 03 › golang-how-to-convert-a-value-to-another-data-type
Golang How to convert string to float, int | Technical Feeder
May 23, 2023 - Cast the value with the type. intValue := 128 fmt.Println(float64(intValue)) // 128 fmt.Println(float32(intValue)) // 128 // fmt.Printf format %f has arg intValue of wrong type int fmt.Printf("%f\n", intValue) // %!f(int=128) fmt.Printf("%f\n", ...