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

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

本文介绍了如何使用Go将浮点数字格式化为字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用Go我试图找到将浮点数格式化为字符串的最佳方法。我已经找过例子,但是我找不到任何具体回答我的问题。我想要做的就是使用最佳方法将浮点数格式化为字符串。小数位数可能会有所不同,但会是已知的(例如2或4或零)。
我想要实现的一个例子如下。
根据下面的例子,我应该使用
fmt.Sprintf()

strconv.FormatFloat()

其他的东西?
和,每个的正常用法和每个之间的差异是什么?



我也不明白在下面使用32或64的意义目前有32个:

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

$ b

   fmt.Sprintf 和 strconv.FormatFloat 在封面下使用相同的字符串格式化例程,所以应该给出相同的结果。



如果数字应该被格式化的精度是可变的,那么使用 FormatFloat 可能更容易,因为它避免了需要像使用 Sprintf 一样构造格式字符串。

FormatFloat 的最后一个参数控制值的四舍五入方式。从文档:

所以如果你正在处理 float32 code> values,然后传递 32 是正确的。


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)

}
解决方案

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:

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

这篇关于如何使用Go将浮点数字格式化为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 08:28