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 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?