Go fmt float64问题

huangapple go评论79阅读模式
英文:

Go fmt float64 issue

问题

我在理解go fmt包方面遇到了一个小问题。

它与以下代码有关:

import "fmt"

func main() {
var smallFloat float64 = 0.123456789
var bigFloat float64 = 123456789000

fmt.Println(fmt.Sprintf("%f", smallFloat))
fmt.Println(fmt.Sprintf("%f", bigFloat))

}

输出结果为:

0.123457
123456789000.000000

我不想使用科学计数法,所以认为%f符合我的需求。我从格式化页面(https://golang.org/pkg/fmt/)上看到,它说:

%e和%f的默认精度为6;对于%g,它是最小的数字位数,足以唯一标识该值。

有没有办法可以使用fmt包,使我能够表示smallFloat的完整小数值,同时又不在bigFloat的末尾添加6个零?

英文:

I've come across a bit of a gotcha in my noob understanding of go fmt package

It relates to the following code:

import "fmt"

func main() {
    var smallFloat float64 = 0.123456789
    var bigFloat float64 = 123456789000

    fmt.Println(fmt.Sprintf("%f", smallFloat))
    fmt.Println(fmt.Sprintf("%f", bigFloat))
}

The output is:

0.123457
123456789000.000000

I don't want to use scientific notation so thought %f would suit my needs.I can see from the formatting page (https://golang.org/pkg/fmt/) it says:

The default precision for %e and %f is 6; for %g it is the smallest number of digits necessary to identify the value uniquely.

Is there a way I can use the fmt package that would allow me represent the full decimal value of smallFloat while at the same time not appending 6 zeros to the end of bigFloat?

答案1

得分: 5

你可以使用strconv.FormatFloat,将prec设置为-1:

fmt.Println(strconv.FormatFloat(big, 'f', -1, 64))
fmt.Println(strconv.FormatFloat(small, 'f', -1, 64))

输出结果为:

123456789000
0.123456789

Playground: http://play.golang.org/p/7p8xnQ_BzE.

英文:

You can use strconv.FormatFloat with prec set to -1:

fmt.Println(strconv.FormatFloat(big, 'f', -1, 64))
fmt.Println(strconv.FormatFloat(small, 'f', -1, 64))

prints

123456789000
0.123456789

Playground: http://play.golang.org/p/7p8xnQ_BzE.

huangapple
  • 本文由 发表于 2016年3月9日 23:39:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/35896054.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定