Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to format floating point numbers into a string using Go

Tags:

Using Go I'm trying to find the "best" way to format a floating point number into a string. I've looked for examples however I cannot find anything that specifically answers the questions I have. All I want to do is use the "best" method to format a floating point number into a string. The number of decimal places may vary but will be known (eg. 2 or 4 or zero). An example of what I want to achieve is below.

Based on the example below should I use fmt.Sprintf() or strconv.FormatFloat() or something else?

And, what is the normal usage of each and differences between each?

I also don't understand the significance of using either 32 or 64 in the following which currently has 32:

strconv.FormatFloat(float64(fResult), 'f', 2, 32)

Example:

package main

import (
    "fmt"
    "strconv"
)

func main() {

    var (
        fAmt1 float32 = 999.99
        fAmt2 float32 = 222.22
    )

    var fResult float32 = float32(int32(fAmt1*100) + int32(fAmt2*100)) / 100

    var sResult1 string = fmt.Sprintf("%.2f", fResult)

    println("Sprintf value = " + sResult1)

    var sResult2 string = strconv.FormatFloat(float64(fResult), 'f', 2, 32)

    println("FormatFloat value = " + sResult2)

}
like image 931
Brian Oh Avatar asked Sep 23 '13 03:09

Brian Oh


People also ask

What is %s in Golang?

The %s expects a string value and the %d an integer value. res := fmt.Sprintf("%s is %d years old", name, age) The fmt. Sprintf function formats a string into a variable. $ go run fmt_funs.go Jane is 17 years old Jane is 17 years old.

What verb is used for floating point number in Golang?

You can convert a number to a floating-point figure with the %f verb.

Which function converts float data to string?

We can convert float to a string easily using str() function.


1 Answers

Both fmt.Sprintf and strconv.FormatFloat use the same string formatting routine under the covers, so should give the same results.

If the precision that the number should be formatted to is variable, then it is probably easier to use FormatFloat, since it avoids the need to construct a format string as you would with Sprintf. If it never changes, then you could use either.

The last argument to FormatFloat controls how values are rounded. From the documentation:

It rounds the result assuming that the original was obtained from a floating-point value of bitSize bits (32 for float32, 64 for float64)

So if you are working with float32 values as in your sample code, then passing 32 is correct.

like image 133
James Henstridge Avatar answered Sep 20 '22 05:09

James Henstridge