float64 的值可以支持多小?
How small the value of float64 can support with?
我从 api 请求中获取数据并根据该值执行计算。
假设我的银行账户或加密账户的余额为 301.38481999999999
我想提现所有的钱,但是golang中的float64
变量自动将变量四舍五入为301.38482
导致提现操作失败,因为我没有那么多钱在我的帐户中。
package main
import(
"log"
)
func main(){
var myvar float64
myvar = 301.38481999999999
log.Println(myvar)
}
https://play.golang.org/p/BXk9fcVJZVn
显示
301.38482
我怎样才能得到准确的余额和确切的数字,以便我可以全部提取?
您将看到的输出与您拥有的实际值混淆了。如果你 check the docs of fmt
:
For floating-point values, width sets the minimum width of the field and precision sets the number of places after the decimal, if appropriate, except that for %g/%G precision sets the maximum number of significant digits (trailing zeros are removed). For example, given 12.345 the format %6.3f prints 12.345 while %.3g prints 12.3. The default precision for %e, %f and %#g is 6; for %g it is the smallest number of digits necessary to identify the value uniquely.
fmt.Println
始终对您传入的任何值使用默认精度。要查看更高的精度,请指定更高的精度:
var myvar float64
myvar = 301.38481999999999
log.Printf("%.20f", myvar)
// 301.38481999999999061401
https://play.golang.org/p/T4iyQcHY4qi
无论打印什么,所有内部运算都将以值的完全精度进行。如果您需要比 float64 提供的更精确,请参阅 math/big
包。
我从 api 请求中获取数据并根据该值执行计算。
假设我的银行账户或加密账户的余额为 301.38481999999999
我想提现所有的钱,但是golang中的float64
变量自动将变量四舍五入为301.38482
导致提现操作失败,因为我没有那么多钱在我的帐户中。
package main
import(
"log"
)
func main(){
var myvar float64
myvar = 301.38481999999999
log.Println(myvar)
}
https://play.golang.org/p/BXk9fcVJZVn
显示
301.38482
我怎样才能得到准确的余额和确切的数字,以便我可以全部提取?
您将看到的输出与您拥有的实际值混淆了。如果你 check the docs of fmt
:
For floating-point values, width sets the minimum width of the field and precision sets the number of places after the decimal, if appropriate, except that for %g/%G precision sets the maximum number of significant digits (trailing zeros are removed). For example, given 12.345 the format %6.3f prints 12.345 while %.3g prints 12.3. The default precision for %e, %f and %#g is 6; for %g it is the smallest number of digits necessary to identify the value uniquely.
fmt.Println
始终对您传入的任何值使用默认精度。要查看更高的精度,请指定更高的精度:
var myvar float64
myvar = 301.38481999999999
log.Printf("%.20f", myvar)
// 301.38481999999999061401
https://play.golang.org/p/T4iyQcHY4qi
无论打印什么,所有内部运算都将以值的完全精度进行。如果您需要比 float64 提供的更精确,请参阅 math/big
包。