formatFloat : convert float number to string

Go

Go Problem Overview


http://golang.org/pkg/strconv/

http://play.golang.org/p/4VNRgW8WoB

How do I convert a float number into string format? This is google playground but not getting the expected output. (2e+07) I want to get "21312421.213123"

package main

import "fmt"
import "strconv"

func floattostr(input_num float64) string {

     	// to convert a float number to a string
    return strconv.FormatFloat(input_num, 'g', 1, 64)
 }

 func main() {
      fmt.Println(floattostr(21312421.213123))
      // what I expect is "21312421.213123" in string format
 }

Please help me get the string out of float number. Thanks

Go Solutions


Solution 1 - Go

Try this

package main

import "fmt"
import "strconv"

func FloatToString(input_num float64) string {
   	// to convert a float number to a string
	return strconv.FormatFloat(input_num, 'f', 6, 64)
}

func main() {
	fmt.Println(FloatToString(21312421.213123))
}

If you just want as many digits precision as possible, then the special precision -1 uses the smallest number of digits necessary such that ParseFloat will return f exactly. Eg

strconv.FormatFloat(input_num, 'f', -1, 64)

Personally I find fmt easier to use. (Playground link)

fmt.Printf("x = %.6f\n", 21312421.213123)

Or if you just want to convert the string

fmt.Sprintf("%.6f", 21312421.213123)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser2671513View Question on Stackoverflow
Solution 1 - GoNick Craig-WoodView Answer on Stackoverflow