[Solved] replicate javascript unsafe numbers in golang [closed]


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"
)

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

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

solved replicate javascript unsafe numbers in golang [closed]