英文:
Float to string in Golang with a minimum width
问题
我正在尝试使用fmt.Printf
将一个浮点数打印出来,要求最小宽度为3。
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
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
这个函数应该可以实现你想要的功能:
func Float2String(i float64) string {
// 首先判断小数点后是否有2位或更少的有效数字,
// 如果是,则返回带有最多2个尾随0的数字。
if i*100 == math.Floor(i*100) {
return strconv.FormatFloat(i, 'f', 2, 64)
}
// 否则,按照正常方式格式化,使用最少数量的必要数字。
return strconv.FormatFloat(i, 'f', -1, 64)
}
希望对你有帮助!
英文:
This function should do what you want:
func Float2String(i float64) string {
// First see if we have 2 or fewer significant decimal places,
// and if so, return the number with up to 2 trailing 0s.
if i*100 == math.Floor(i*100) {
return strconv.FormatFloat(i, 'f', 2, 64)
}
// Otherwise, just format normally, using the minimum number of
// necessary digits.
return strconv.FormatFloat(i, 'f', -1, 64)
}
答案2
得分: 3
使用strconv.FormatFloat
进行格式化,例如像这样:
package main
import (
"fmt"
"strconv"
)
func main() {
fmt.Println(strconv.FormatFloat(0, 'f', 2, 64))
fmt.Println(strconv.FormatFloat(0.0000003, 'f', -1, 64))
}
输出结果为:
0.00
0.0000003
请参阅链接的文档以了解其他格式化选项和模式。
英文:
Use strconv.FormatFloat
, for example, like this:
https://play.golang.org/p/wNe3b6d7p0
package main
import (
"fmt"
"strconv"
)
func main() {
fmt.Println(strconv.FormatFloat(0, 'f', 2, 64))
fmt.Println(strconv.FormatFloat(0.0000003, 'f', -1, 64))
}
> 0.00<br>
> 0.0000003
See the linked documentation for other formatting options and modes.
答案3
得分: 0
你缺少一个点。
fmt.Printf("%.3f", float64(0))
将打印出:0.000
示例:https://play.golang.org/p/n6Goz3ULcm
英文:
You are missing a dot
fmt.Printf("%.3f", float64(0))
will print out: 0.000
Example: https://play.golang.org/p/n6Goz3ULcm
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论