Skip to content Skip to sidebar Skip to footer

Replicate Javascript Unsafe Numbers In Golang

So in go, I do a calculation which gives '5726718050568503296' In JS it gives '5726718050568503000' I would like to replicate this behavior in go

Solution 1:

As discussed in the comments of Why is 5726718050568503296 truncated in JS as others have mentioned, this is caused by the way toString() is implemented in JavaScript which appears to use the minimium number of significant digits to return the same represented number, rather than returning the mathematically closest number. You can however replicate this behaviour in Go by using the special -1 precision with strconv.FormatFloat:

package main

import (
    "fmt""strconv"
)

funcmain() {
    n, _ := strconv.ParseInt(strconv.FormatFloat(5726718050568503296.0, 'f', -1, 64), 10, 64)
    fmt.Println(n)
}

Playground link: https://play.golang.org/p/9ZObcB3so4o

Solution 2:

Seems like there is no easy way around it. JS has its way of representing the Number type and the integer you presented basically overflows the capacity of it. Please refer to: https://stackoverflow.com/a/1379973/10316247 for more information about how JS handles this and why this wierd behavior happens.

Replicate that in go would be very very trick as you'd need to look at the byte representation of this int and try to assume how JS would handle it.

I would (as the link above suggests) use it as and string.

Post a Comment for "Replicate Javascript Unsafe Numbers In Golang"