Formatting Float Values

We all need to format float numbers before displaying them to users. In Golang we can use the FormatFloat() method in strconv package

Here is a brief overview of how to use FormatFloat()

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

FormatFloat() accepts 4 parameters and returns formatted number as string.

The first parameter is the number you want to format, the second parameter is the way you want to format that number (We will explore this more in examples), the third parameter is the decimal point precision and fourth parameter is based on whether we are using float32 or a float64 (Use 32 for float32 and 64 for float64)

Let us see a few examples. For all our examples, we use a variable “expires_in” with value 1243142342.53245235252 . So

expires_in := 1243142342.53245235252

Lets start exploring now

strconv.FormatFloat(float64(expires_in), 'f', 2, 64)

We are converting expires_in to a decimal number ( “f” refers to a decimal) with precision of 2 decimal points.

Its output is : 1243142342.53

If we change the precision to 0

strconv.FormatFloat(float64(expires_in), 'f', 0, 64)

The output is : 1243142343 (Note the rounding off!)

If you want exponential format

strconv.FormatFloat(float64(expires_in), 'e', 2, 64)

Outputs : 1.24e+09

Similarly, there is FormatInt() function too which does the job for integer values.

Hope this helps!

~~ Whizdumb ~~
Email : sachin.xpert@gmail.com