formatFloat:将float number转换为string

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)

  • 我用"FloatFormat"中的精度-1更新了答案,这是你想要的. (3认同)
  • `strconv.FormatFloat` +1 - 我没有意识到这一点,但可能值得注意的是,`fmt` 虽然使用起来更好,但会比直接函数调用慢一点,因为它必须这样做大量解析只是为了弄清楚你想要什么,然后才调用“strconv.FormatFloat”。 (2认同)
  • @Bruce'f'控制格式 - 有关详细信息,请参阅[文档](https://golang.org/pkg/strconv/#FormatFloat). (2认同)