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

5 years ago Lalit Bhagtani 0

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

FormatFloat

The function FormatFloat converts the floating point number to a string value according to the format and precision passed as an argument. It rounds the result value, by assuming that the original value was obtained from a floating point value of a bitSize bits (32 for float32 and 64 for float64).

The format could be one of the following type :-

  1. ‘b’ is used for binary exponent, its output format is -ddddp±ddd
  2. ‘e’ and ‘E’ is used for decimal exponent, output format for ‘e’ is -d.dddde±dd and for ‘E’ -d.ddddE±dd
  3. ‘f’ is used when exponent is not needed, its output format is -ddd.dddd
  4. ‘g’ is used as ‘e’ when number is large and as ‘f’ when number is small
  5. ‘G’ is used as ‘E’ when number is large and as ‘F’ when number is small
  6. ‘x’ and ‘X’ is used for hexadecimal fraction and binary exponent, output format for ‘x’ is -0xd.ddddp±ddd and for ‘X’ is -0Xd.ddddP±ddd

The precision controls the number of digits (excluding the exponent) printed by the ‘e’, ‘E’, ‘f’, ‘g’, ‘G’, ‘x’, and ‘X’ formats. For ‘e’, ‘E’, ‘f’, ‘x’, and ‘X’, it is the number of digits after the decimal point. For ‘g’ and ‘G’ it is the maximum number of significant digits (trailing zeros are removed). The special precision -1 uses the smallest number of digits necessary such that ParseFloat will return f exactly.

Syntax

func FormatFloat(num float64, format byte, precision int, bitSize int) string

Example

package main

import (
    "fmt"
    "strconv"
)

func main() {

    var (
	Fnum float64 = 10.345
	Snum float64 = 23457810.345
	Tnum float64 = 101.345
    )

    first := strconv.FormatFloat(Fnum, 'b', -1, 32)
    fmt.Printf("%T, %v\n", first, first)

    second := strconv.FormatFloat(Fnum, 'e', -1, 64)
    fmt.Printf("%T, %v\n", second, second)

    third := strconv.FormatFloat(Fnum, 'f', -1, 64)
    fmt.Printf("%T, %v\n", third, third)

    fourth := strconv.FormatFloat(Snum, 'g', -1, 64)
    fmt.Printf("%T, %v\n", fourth, fourth)

    fifth := strconv.FormatFloat(Tnum, 'g', -1, 64)
    fmt.Printf("%T, %v\n", fifth, fifth)
}

Output

string, 10847519p-20
string, 1.0345e+01
string, 10.345
string, 2.3457810345e+07
string, 101.345

References

  1. FormatFloat function Docs

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