在 golang 中使用 big.Float 进行一些计算后,我将精度设置为 2。
即使你的数字只是一个简单的 10,在设置精度后它是 8。
package main
import (
"fmt"
"math/big"
)
func main() {
cost := big.NewFloat(10)
fmt.Println("COST NOW", cost)
perKWh := big.NewFloat(0)
cost.Add(cost, perKWh)
fmt.Println("COST ", cost.String())
perMinute := big.NewFloat(0)
cost.Add(cost, perMinute)
fmt.Println("COST ", cost.String())
discountAmount := big.NewFloat(0)
cost.Sub(cost, discountAmount)
floatCos, _ := cost.Float64()
fmt.Println(fmt.Sprintf("COST FLOAT %v", floatCos))
cost.SetPrec(2)
fmt.Println("COST ", cost.String())
}
在此处检查 Playground 示例:https://play.golang.org/p/JmCRXkD5u49
想知道为什么
最佳答案
来自fine manual :
type Float
[...]
Each Float value also has a precision, rounding mode, and accuracy. The precision is the maximum number of mantissa bits available to represent the value. The rounding mode specifies how a result should be rounded to fit into the mantissa bits, and accuracy describes the rounding error with respect to the exact result.
big.Float
在内部表示为:
sign × mantissa × 2**exponent
当您调用 SetPrec
时您正在设置可用于尾数的位数,而不是数字的十进制表示中的精度位数。
您不能用两位尾数表示十进制 10(二进制 1010),因此它四舍五入为可以放入 2 位的十进制 8(二进制 1000)。您至少需要三位来存储十进制 10 的 101
部分。8 可以放入一个尾数中,因此如果您说 cost.SetPrec(1 )
。
使用大包时,您需要考虑二进制。
关于go - big.Float SetPrec 奇怪的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48819612/