以最小宽度浮动到Golang中的字符串

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.

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)
}

You are missing a dot

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

will print out: 0.000

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

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
0.0000003

See the linked documentation for other formatting options and modes.