最大浮点数宽度

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

Maximum Float Width

问题

在Go语言中,使用fmt.Sprintf函数可以格式化字符串。对于给定的语句fmt.Sprintf("%4.3f", 18.8836),它会返回18.883

如果你想要返回值为18.88,也就是让整个数字都占用4个字符的宽度,而不仅仅是小数部分,是有办法的。

你可以使用以下语句来实现:

fmt.Sprintf("%.2f", 18.8836)

这样,%.2f的格式化字符串将会使得返回值只保留两位小数,而不考虑整个数字的宽度。

英文:

In go, the statement

fmt.Sprintf("%4.3f", 18.8836)

Will return

18.883

Is there a way of making the return value

18.88

In other words, is there a way to make the 4 apply to the whole width of the number and not just the decimal portion?

答案1

得分: 3

你可以使用%g来实现这个功能:

fmt.Printf("%.4g\n", 18.8836)

https://play.golang.org/p/accWeNXG9V

英文:

You can accomplish this with %g:

fmt.Printf("%.4g\n", 18.8836)

https://play.golang.org/p/accWeNXG9V

huangapple
  • 本文由 发表于 2017年6月15日 04:56:33
  • 转载请务必保留本文链接:https://go.coder-hub.com/44554607.html
匿名

发表评论

匿名网友

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

确定