How to change a float64 number to uint64 in a right way?

后端 未结 2 1952
说谎
说谎 2020-12-12 01:57
package main

func main() {
    var n float64 = 6161047830682206209
    println(uint64(n))
}

The output will be:

616104783068220620         


        
2条回答
  •  隐瞒了意图╮
    2020-12-12 02:28

    The problem is not with the conversion but that the number is too large an integer to be stored exactly as a float64. The assignment to n results in some loss of significance.

    If you think about it, your number (about 6e18) is very close to the largest uint64 (2^64-1 or about 18e18). A uint64 uses all of it's 64 bits to store an integer but a float64 must use some of its 64 bits to store an exponent so it's going to have less bits to remember the mantissa.

    In summary, if you assign a uint64 (or integer constant) larger than about 10^15 to a float64 and back to a uint64 you will get a close, but probably not exactly the same, value.

    [BTW Icza's answer is good and correct. I hope this answer is simple summary.]

提交回复
热议问题