How to Convert string to float type in Golang?


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. In this article, we will discuss how to convert a string to a float type in Go.

Syntax

The syntax of the ParseFloat function is as follows −

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

The ParseFloat function takes two arguments - the string to be converted and the bit size of the float type. It returns the converted float value and an error value.

Steps to Convert String to Float Type in Golang

  • Step 1 − Import the strconv package.

import "strconv"
  • Step 2 − Declare a string variable to store the string value.

s := "3.14"
  • Step 3 − Convert the string to a float using the ParseFloat function.

f, err := strconv.ParseFloat(s, 64)
  • Step 4 − Handle the error returned by the ParseFloat function.

if err != nil {
   // Handle the error
}

Example

Here is an example program that demonstrates how to convert a string to a float type in Go −

package main

import (
   "fmt"
   "strconv"
)

func main() {
   s := "3.14"

   f, err := strconv.ParseFloat(s, 64)
   if err != nil {
      fmt.Println("Error:", err)
      return
   }

   fmt.Printf("Type: %T, Value: %v", f, f)
}

Output

Type: float64, Value: 3.14

Conclusion

In this article, we have learned how to convert a string to a float type in Go using the strconv package. We used the ParseFloat function to convert the string to a float type. Remember to handle the error returned by the ParseFloat function, as it may contain valuable information about why the conversion failed.

Updated on: 05-May-2023

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements