對許多程式而言,從字串剖析數字是一項基本的常見任務;以下將說明在Go中如何執行此項作業。
|
|
|

package main
|
內建套件strconv 提供數字剖析功能。
|
import (
"fmt"
"strconv"
)
|
|
func main() {
|
使用ParseFloat ,這個64 代表要剖析多少位元的精度。
|
f, _ := strconv.ParseFloat("1.234", 64)
fmt.Println(f)
|
對於ParseInt ,0 代表從字串推斷進制。64 需要結果符合64位元。
|
i, _ := strconv.ParseInt("123", 0, 64)
fmt.Println(i)
|
ParseInt 會辨識十六進位數字。
|
d, _ := strconv.ParseInt("0x1c8", 0, 64)
fmt.Println(d)
|
ParseUint 亦可用。
|
u, _ := strconv.ParseUint("789", 0, 64)
fmt.Println(u)
|
Atoi 是一個適用於基本10進位int 剖析的便利函數。
|
k, _ := strconv.Atoi("135")
fmt.Println(k)
|
剖析函數會對錯誤的輸入傳回錯誤訊息。
|
_, e := strconv.Atoi("wat")
fmt.Println(e)
}
|