Go,Golang,formatFloat:将浮点数转换为字符串 [英] Go, Golang, formatFloat : convert float number to string

查看:8420
本文介绍了Go,Golang,formatFloat:将浮点数转换为字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



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



如何将浮点数转换为字符串格式?
这是谷歌游乐场,但没有得到预期的输出。 (2e + 07)
我想得到21312421.213123

 包主

importfmt
importstrconv

func floattostr(input_num float64)string {

//将浮点数转换为字符串
返回strconv.FormatFloat(input_num,'g',1,64)
}

func main(){
fmt.Println(floattostr(21312421.213123))
//我期望的是字符串格式的21312421.213123
}

请帮我搞定该字符串不在浮点数中。谢谢

解决方案

试试这个

  package main 

importfmt
importstrconv

func FloatToString(input_num float64)string {
//将浮点数转换为字符串
返回strconv.FormatFloat(input_num,'f',6,64)

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

如果您只想要尽可能多的数字精度,那么特殊精度-1使用必需的最小数字位数,以便ParseFloat将精确返回f。例如

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

我个人觉得 fmt 更易于使用。 ( Playground链接

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

或者if你只是想转换字符串

pre $ $ $ $ $ $ $ $ $ $ $ $ $ code>


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

解决方案

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)

这篇关于Go,Golang,formatFloat:将浮点数转换为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆