How to convert String to Float type in GoLang | GoLang Tutorial

5 years ago Lalit Bhagtani 0

In this tutorial, we will learn about how to convert string to float type in Go programming language.

ParseFloat

The function ParseFloat converts the string to a floating point number with the precision specified by bitSize value passed as an argument. The bitSize value can be of two type, 32 for float32 data type and 64 for float64 data type. When bitSize value is 32, the return value is still of type float64, but it can be cast to float32 without changing its value.

The ParseFloat function accepts decimal and hexadecimal floating point numbers. If string is well formed and close to a valid floating point number, then function returns the closest floating point number rounded using IFFF754 unbiased rounding. If string is not well formed then function returns an error (err.Err = ErrSyntax).

Syntax

func ParseFloat(str string, bitSize int) (float64, error)

Example

package main

import (
    "fmt"
    "strconv"
)

func main() {

    var (
        marksA string = "10.32"
	marksB string = "7.63"
	marksC string = "marks"
    )

    first, _ := strconv.ParseFloat(marksA, 32)
    fmt.Printf("%T, %v\n", first, first)

    second, _ := strconv.ParseFloat(marksB, 64)
    fmt.Printf("%T, %v\n", second, second)

    third, error := strconv.ParseFloat(marksC, 64)
    fmt.Printf("%T, %v, %v\n", third, third, error)
}

Output

float64, 10.319999694824219
float64, 7.63
float64, 0, strconv.ParseFloat: parsing "marks": invalid syntax

References

  1. ParseFloat function Docs

That’s all for how to convert string to float type in Go programming language. if you liked it, please share your thoughts in comments section and share it with others too.