如何使用Go将浮点数字格式化为字符串 [英] How to format floating point numbers into a string using Go
问题描述
我想要实现的一个例子如下。
根据下面的例子,我应该使用
fmt.Sprintf()
或
strconv.FormatFloat()
或
其他的东西?
和,每个的正常用法和每个之间的差异是什么?
我也不明白在下面使用32或64的意义目前有32个:
$ $ $ $ $ $ $ $ $ strconv.FormatFloat(float64(fResult),'f',2,32)
包主要
导入(
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)
$ b println(FormatFloat value =+ sResult2)
fmt.Sprintf
和 strconv.FormatFloat
在封面下使用相同的字符串格式化例程,所以应该给出相同的结果。 如果数字应该被格式化的精度是可变的,那么使用 FormatFloat
可能更容易,因为它避免了需要像使用 Sprintf
一样构造格式字符串。
FormatFloat
的最后一个参数控制值的四舍五入方式。从文档:
假设原始数据是从浮点数
中获得的bitSize位(32为float32,64为float64)
所以如果你正在处理 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:
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.
这篇关于如何使用Go将浮点数字格式化为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!