dtbhp60824
dtbhp60824
2013-09-30 18:40
浏览 73
已采纳

formatFloat:将浮点数转换为字符串[重复]

This question already has an answer here:

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

</div>

图片转代码服务由CSDN问答提供 功能建议

此问题已经存在 在这里有答案:

  • 如何使用Go将浮点数格式化为字符串 2个答案

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

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

    如何将浮点数转换为字符串格式? 是google游乐场,但未获得预期的输出。 (2e + 07) 我想获取“ 21312421.213123”

     包main 
     
    import“ fmt” 
    import“ strconv” 
     
    func floattostr(input_num float64) 字符串{
     
     //将浮点数转换为字符串
    返回strconv.FormatFloat(input_num,'g',1,64)
    } 
     
     func main(){
     fmt.Println  (floattostr(21312421.213123))
     //我期望的是字符串格式的“ 21312421.213123” 
    } 
       
     
     

    请帮助我从浮点数中获取字符串 。 谢谢

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • duanhui7329
    duanhui7329 2013-09-30 18:56
    已采纳

    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
    ", 21312421.213123)
    

    Or if you just want to convert the string

    fmt.Sprintf("%.6f", 21312421.213123)
    
    点赞 评论

相关推荐