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.
func FormatFloat(f float64, fmt byte, prec, bitSize int) string
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
).The function FormatFloat()
returns the given floating-point in the string format.
The following code shows how to use the strconv.FormatFloat()
in Golang:
// Using strconv.FormatFloat() Functionpackage mainimport ("fmt""strconv""reflect")func main() {// declaring variablevar num float64// Assign valuenum = 26.345// returns a string typefmt.Println(strconv.FormatFloat(num, 'f', 0, 64))fmt.Println(reflect.TypeOf(strconv.FormatFloat(num, 'f', 0, 64))) // print the typefmt.Println()// reassign valuenum = -17.96// returns a string typefmt.Println(strconv.FormatFloat(num, 'G', 2, 64))fmt.Println()// reassign valuenum = 0.235// returns a string typefmt.Println(strconv.FormatFloat(num, 'E', -1, 64))}
main
package.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.