How to use the strconv.FormatFloat() function in Golang

Overview

The FormatFloat() function in the strconv package is used to convert a given floating-point number f to a string.

The formatting is done using the format fmt and precision prec parameters.

Syntax

func FormatFloat(f float64, fmt byte, prec, bitSize int) string

Parameters

  • f: The floating-point number to be converted in the string form.
  • fmt: A byte value to specify the format.
'b' (-ddddp±ddd, a binary exponent),
'e' (-d.dddde±dd, a decimal exponent),
'E' (-d.ddddE±dd, a decimal exponent),
'f' (-ddd.dddd, no exponent),
'g' ('e' for large exponents, 'f' otherwise),
'G' ('E' for large exponents, 'f' otherwise),
'x' (-0xd.ddddp±ddd, a hexadecimal fraction and binary exponent), or
'X' (-0Xd.ddddP±ddd, a hexadecimal fraction and binary exponent).
  • prec: The precision value that determines the number of digits printed by the e, E, f, g, G, x, and X formats (excluding the exponent). prec is the number of digits after the decimal point for the format value (e, E, f, x, and X).
  • bitSize : An integer value to define the bitSize bits (32 for float32, 64 for float64).

Return value

The function FormatFloat() returns the given floating-point in the string format.

Code

The following code shows how to use the strconv.FormatFloat() in Golang:

// Using strconv.FormatFloat() Function
package main
import (
"fmt"
"strconv"
"reflect"
)
func main() {
// declaring variable
var num float64
// Assign value
num = 26.345
// returns a string type
fmt.Println(strconv.FormatFloat(num, 'f', 0, 64))
fmt.Println(reflect.TypeOf(strconv.FormatFloat(num, 'f', 0, 64))) // print the type
fmt.Println()
// reassign value
num = -17.96
// returns a string type
fmt.Println(strconv.FormatFloat(num, 'G', 2, 64))
fmt.Println()
// reassign value
num = 0.235
// returns a string type
fmt.Println(strconv.FormatFloat(num, 'E', -1, 64))
}

Code explanation

  • Line 4: we add the main package.
  • Lines 6 to 9: we import the necessary packages.
  • Lines 11 to 31: we define the main() function, variable num of Float64 type, and assign a value to it. Next, we pass the variable to the FormatFloat() function which converts the num value to a string given the fmt, prec, and bitSize parameters.

Free Resources