Search code examples
goieee-754

It it safe to convert from int64 to float64?


As far as I know int64 can be converted in float64 in Go, the language allows this with float64(some_int64_variable), but I also know that not all 64 bit signed integers can be represented in double (because of IEE754 approximations).

We have some code which receives the price of an item in cents using int64 and does something like

const TB                    = 1 << 40

func ComputeSomething(numBytes int64) {
    Terabytes := float64(numBytes) / float64(TB)

I'm wondering how safe this is, since not all integers can be represented with doubles.


Solution

  • Depends on what you mean by "safe".

    Yes, precision can be lost here in some cases. float64 cannot represent all values of int64 precisely (since it only has 53 bits of mantissa). So if you need a completely accurate result, this function is not "safe"; if you want to represent money in float64 you may get into trouble.

    On the other hand, do you really need the number of terabytes with absolute precision? Will numBytes actually divide by TB accurately? That's pretty unlikely, but it all depends on your specification and needs. If your code has a counter of bytes and you want to display approximately how many TB it is (e.g. 0.05 TB or 2.124 TB) then this calculation is fine.