为什么浮点数字舍入在go中不准确



我使用%0.1f将浮点值四舍五入到小数点后1位。然而,我在四舍五入方面得到了不同的结果。

package main
import "fmt"
func format() {
name := "Granth"
age := 28
fmt.Print("my name is ", name, " and my age is ", age, "n")
fmt.Printf("my name is %v and my age is %vn", name, age)
fmt.Printf("my name is %q and my age is %vn", name, age)
fmt.Printf("my name is %q and my age is %qn", name, age)
fmt.Printf("name type is %T and age type is %Tn", name, age)
fmt.Printf("the float is %fn", 34.55)
fmt.Printf("the float rounded off is %0.1fn", 35.55)
fmt.Printf("the float rounded off is %0.1fn", 25.55)
}

输出为:-

my name is Granth and my age is 28
my name is Granth and my age is 28
my name is "Granth" and my age is 28
my name is "Granth" and my age is 'x1c'
name type is string and age type is int
the float is 34.550000
the float rounded off is 35.5
the float rounded off is 25.6

为什么它显示35.55四舍五入为35.5,25.55四舍五进为25.6?

go版本go1.19.1 windows/am64

您的演示文稿中没有一个提供所有有效数字,少数十进制真实值可以在机器级使用的二进制浮点中精确表示。

因此,例如,如果35.55实际上存储在二进制浮点中,更接近于35.550000000001,当显示到小数点后一位时,它将变为35.6,而如果25.55更准确地说是25.5499999999999,当显示到小数位后一位,它将四舍五入到25.5,25.55到小数点二位。

要演示这一点,请显示25.55到更多的小数位数。我不熟悉go,它处理的是实数表示,但IEEE-754双精度二进制浮点可以表示十进制实数,精度约为15有效位数。因此,在15个重要数字之后,任何不精确性都将显而易见。

最新更新