简体   繁体   English

float64 的值可以支持多小?

[英]How small the value of float64 can support with?

I get data from an api request and perform a calculation based on the value.我从 api 请求中获取数据并根据该值执行计算。

Let say my bank account or crypto account have a balance of 301.38481999999999假设我的银行账户或加密账户的余额为301.38481999999999

I want to withdraw all of the money, but the float64 variable in golang automatically round up the variable to 301.38482 which caused the withdrawal operation to fail because I do not have that much money in my account.我想提取所有的钱,但是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 https://play.golang.org/p/BXk9fcVJZVn

It show它显示

301.38482

How can I get the exact balance with exact number so that I can withdraw all of it?我怎样才能得到确切数字的确切余额,以便我可以将其全部提取?

You're confusing the output you see with the actual value you have.您将看到的 output 与您拥有的实际值混淆了。 If you check the docs of fmt :如果您查看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).对于浮点值,宽度设置字段的最小宽度,精度设置小数点后的位数(如果适用),除了 %g/%G 精度设置有效数字的最大数量(删除尾随零) . For example, given 12.345 the format %6.3f prints 12.345 while %.3g prints 12.3.例如,给定 12.345 格式 %6.3f 打印 12.345 而 %.3g 打印 12.3。 The default precision for %e, %f and %#g is 6; %e、%f 和 %#g 的默认精度为 6; for %g it is the smallest number of digits necessary to identify the value uniquely.对于 %g,它是唯一标识该值所需的最小位数。

fmt.Println always uses the default precision for whatever value you pass in. To see more precision, specify more precision: fmt.Println始终对您传入的任何值使用默认精度。要查看更高的精度,请指定更高的精度:

var myvar float64
myvar = 301.38481999999999
log.Printf("%.20f", myvar)

// 301.38481999999999061401

https://play.golang.org/p/T4iyQcHY4qi https://play.golang.org/p/T4iyQcHY4qi

Regardless of what's printed, all internal arithmetic will be done with the full precision of the value.无论打印什么,所有内部算术都将以该值的完整精度完成。 If you need more precision than float64 provides, see the math/big package.如果您需要比 float64 提供的精度更高的精度,请参阅math/big package。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM