2016-10-27 14 views
1

我試圖得到一個浮動使用fmt.Printf與3浮點數到字符串中Golang與最小寬度

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

的最小寬度應打印0.00打印,但它不是打印0.000000 如果我將精度設置爲3,它將截斷值。

基本上,我想要的是,如果值爲0,它應該打印0.00。如果該值爲0.045,它應該打印0.045

回答

2

這個函數應該做你想要什麼:

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

我希望它在小數點後打印最少2個位置,但它將具有打印整個值的精度。 – Fluffy

+0

是的,那正好 – Fluffy

1

使用strconv.FormatFloat,例如,像這樣:

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

查看其他格式選項和模式所鏈接的文檔。

相關問題