48 go
http://golang.org/pkg/strconv/
http://play.golang.org/p/4VNRgW8WoB
如何将浮点数转换为字符串格式?这是谷歌游乐场,但没有得到预期的输出.(2e + 07)我想得到"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
}
Run Code Online (Sandbox Code Playgroud)
请帮我从浮点数中取出字符串.谢谢
Nic*_*ood 122
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))
}
Run Code Online (Sandbox Code Playgroud)
如果您只想要尽可能多的数字精度,那么特殊精度-1使用所需的最小位数,以便ParseFloat将精确返回f.例如
strconv.FormatFloat(input_num, 'f', -1, 64)
Run Code Online (Sandbox Code Playgroud)
我个人觉得fmt更容易使用.(游乐场链接)
fmt.Printf("x = %.6f\n", 21312421.213123)
Run Code Online (Sandbox Code Playgroud)
或者,如果您只想转换字符串
fmt.Sprintf("%.6f", 21312421.213123)
Run Code Online (Sandbox Code Playgroud)