drrc61668568 2013-09-23 03:27
浏览 147
已采纳

如何使用Go将浮点数格式化为字符串

Using Go I'm trying to find the "best" way to format a floating point number into a string. I've looked for examples however I cannot find anything that specifically answers the questions I have. All I want to do is use the "best" method to format a floating point number into a string. The number of decimal places may vary but will be known (eg. 2 or 4 or zero). An example of what I want to achieve is below. Based on the example below should I use fmt.Sprintf() or strconv.FormatFloat() or something else? and, what is the normal usage of each and differences between each?

I also don't understand the significance of using either 32 or 64 in the following which currently has 32 :

strconv.FormatFloat(float64(fResult), 'f', 2, 32)

Example:

package main

import (
    "fmt"
    "strconv"
)

func main() {

    var (
        fAmt1 float32 = 999.99
        fAmt2 float32 = 222.22
    )

    var fResult float32 = float32(int32(fAmt1*100) +int32(fAmt2*100)) / 100

    var sResult1 string = fmt.Sprintf("%.2f", fResult)

    println("Sprintf value = " + sResult1)

    var sResult2 string = strconv.FormatFloat(float64(fResult), 'f', 2, 32)

    println("FormatFloat value = " + sResult2)

}
  • 写回答

2条回答 默认 最新

  • doufei4923 2013-09-23 03:49
    关注

    Both fmt.Sprintf and strconv.FormatFloat use the same string formatting routine under the covers, so should give the same results.

    If the precision that the number should be formatted to is variable, then it is probably easier to use FormatFloat, since it avoids the need to construct a format string as you would with Sprintf. If it never changes, then you could use either.

    The last argument to FormatFloat controls how values are rounded. From the documentation:

    It rounds the result assuming that the original was obtained from a floating-point value of bitSize bits (32 for float32, 64 for float64)

    So if you are working with float32 values as in your sample code, then passing 32 is correct.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 想问一下stata17中这段代码哪里有问题呀
  • ¥15 flink cdc无法实时同步mysql数据
  • ¥100 有人会搭建GPT-J-6B框架吗?有偿
  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决