Float to string in Golang with a minimum width

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

Float to string in Golang with a minimum width

问题

我正在尝试使用fmt.Printf将一个浮点数打印出来,要求最小宽度为3。

  1. fmt.Printf("%3f", float64(0))

预期输出应该是0.00,但实际输出是0.000000。如果我设置精度为3,它会截断数值。

基本上,我希望如果数值为0,它应该打印0.00。如果数值为0.045,它应该打印0.045,依此类推。

英文:

I'm trying to get a float to print using fmt.Printf with a minimum width of 3

  1. fmt.Printf("%3f", float64(0))

Should print 0.00, but it instead prints 0.000000
If I set the precision to 3, it truncates the value.

Basically, what I want is if the value is 0, it should print 0.00. If the value is 0.045, it should print 0.045, etc.

答案1

得分: 3

这个函数应该可以实现你想要的功能:

  1. func Float2String(i float64) string {
  2. // 首先判断小数点后是否有2位或更少的有效数字,
  3. // 如果是,则返回带有最多2个尾随0的数字。
  4. if i*100 == math.Floor(i*100) {
  5. return strconv.FormatFloat(i, 'f', 2, 64)
  6. }
  7. // 否则,按照正常方式格式化,使用最少数量的必要数字。
  8. return strconv.FormatFloat(i, 'f', -1, 64)
  9. }

希望对你有帮助!

英文:

This function should do what you want:

  1. func Float2String(i float64) string {
  2. // First see if we have 2 or fewer significant decimal places,
  3. // and if so, return the number with up to 2 trailing 0s.
  4. if i*100 == math.Floor(i*100) {
  5. return strconv.FormatFloat(i, 'f', 2, 64)
  6. }
  7. // Otherwise, just format normally, using the minimum number of
  8. // necessary digits.
  9. return strconv.FormatFloat(i, 'f', -1, 64)
  10. }

答案2

得分: 3

使用strconv.FormatFloat进行格式化,例如像这样:

  1. package main
  2. import (
  3. "fmt"
  4. "strconv"
  5. )
  6. func main() {
  7. fmt.Println(strconv.FormatFloat(0, 'f', 2, 64))
  8. fmt.Println(strconv.FormatFloat(0.0000003, 'f', -1, 64))
  9. }

输出结果为:

0.00
0.0000003

请参阅链接的文档以了解其他格式化选项和模式。

英文:

Use strconv.FormatFloat, for example, like this:

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

  1. package main
  2. import (
  3. "fmt"
  4. "strconv"
  5. )
  6. func main() {
  7. fmt.Println(strconv.FormatFloat(0, 'f', 2, 64))
  8. fmt.Println(strconv.FormatFloat(0.0000003, 'f', -1, 64))
  9. }

> 0.00<br>
> 0.0000003

See the linked documentation for other formatting options and modes.

答案3

得分: 0

你缺少一个点。

  1. fmt.Printf("%.3f", float64(0))

将打印出:0.000

示例:https://play.golang.org/p/n6Goz3ULcm

英文:

You are missing a dot

  1. fmt.Printf(&quot;%.3f&quot;, float64(0))

will print out: 0.000

Example: https://play.golang.org/p/n6Goz3ULcm

huangapple
  • 本文由 发表于 2016年10月27日 20:54:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/40285127.html
匿名

发表评论

匿名网友

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

确定