Golang四捨五入保留兩位小數

Sprintf

四捨六入:web

value, _ := strconv.ParseFloat(fmt.Sprintf("%.2f", 9.824), 64)
	fmt.Println(value) //9.82

	value, _ = strconv.ParseFloat(fmt.Sprintf("%.2f", 9.826), 64)
	fmt.Println(value) //9.83

第三位爲5且5以後有有效數字,知足五入:svg

value, _ := strconv.ParseFloat(fmt.Sprintf("%.2f", 9.8251), 64)
	fmt.Println(value) //9.83

	value, _ = strconv.ParseFloat(fmt.Sprintf("%.2f", 9.8351), 64)
	fmt.Println(value) //9.84

第三位爲5且5以後沒有有效數字:
網上有人說,第二位爲奇數則進位,第二位爲偶數則捨去,例如:spa

value, _ := strconv.ParseFloat(fmt.Sprintf("%.2f", 9.825), 64)
	fmt.Println(value) //9.82

	value, _ = strconv.ParseFloat(fmt.Sprintf("%.2f", 9.835), 64)
	fmt.Println(value) //9.84

可是:code

value, _ := strconv.ParseFloat(fmt.Sprintf("%.2f", 9.815), 64)
	fmt.Println(value) //9.81 竟然捨去了

	value, _ = strconv.ParseFloat(fmt.Sprintf("%.2f", 9.845), 64)
	fmt.Println(value) //9.85 竟然進位了

因此,若是想知足正常的四捨五入邏輯,最好不要使用Sprintf處理。orm

math.Trunc

fmt.Println(math.Trunc(9.815*1e2+0.5)*1e-2) //9.82
	fmt.Println(math.Trunc(9.825*1e2+0.5)*1e-2) //9.83
	fmt.Println(math.Trunc(9.835*1e2+0.5)*1e-2) //9.84
	fmt.Println(math.Trunc(9.845*1e2+0.5)*1e-2) //9.85

以上結果顯示符合四捨五入,可是偶爾會出現精度問題:xml

fmt.Println(math.Trunc(3.3*1e2+0.5)*1e-2) //3.3000000000000003
	fmt.Println(math.Trunc(3.3000000000000003*1e2+0.5) * 1e-2) //3.3000000000000003

一樣使用Trunc,稍做調整:token

n10 := math.Pow10(2)
	fmt.Println(math.Trunc((9.815+0.5/n10)*n10) / n10) //9.82
	fmt.Println(math.Trunc((9.825+0.5/n10)*n10) / n10) //9.83
	fmt.Println(math.Trunc((9.835+0.5/n10)*n10) / n10) //9.84
	fmt.Println(math.Trunc((9.845+0.5/n10)*n10) / n10) //9.85
	fmt.Println(math.Trunc((3.3+0.5/n10)*n10) / n10) //3.3
	fmt.Println(math.Trunc((3.3000000000000003+0.5/n10)*n10) / n10) //3.3

符合四捨五入規則。string

若是要固定顯示兩位小數,需轉換爲string類型,前提是傳入的數值,已經作過兩位小數處理,不然依舊有進位問題:it

value := strconv.FormatFloat(3, 'f', 2, 64)
	fmt.Println(value) //3.00
	
	value = strconv.FormatFloat(3.3, 'f', 2, 64)
	fmt.Println(value) //3.30

	value = strconv.FormatFloat(9.815, 'f', 2, 64)
	fmt.Println(value) //9.81 被捨去

	value = strconv.FormatFloat(9.82, 'f', 2, 64)
	fmt.Println(value) //9.82

公衆號:李田路口io

相關文章
相關標籤/搜索