-2

So in go, I do a calculation which gives "5726718050568503296" In JS it gives "5726718050568503000"

I would like to replicate this behavior in go

user41599
  • 7
  • 4

2 Answers2

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

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

1lann
  • 647
  • 7
  • 11
0

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.

nicolasassi
  • 490
  • 4
  • 14
  • It's not a problem in a different language. It has nothing JS-specific at all. – zerkms Apr 23 '21 at 00:00
  • You're right. Just edited my answer – nicolasassi Apr 23 '21 at 00:21
  • "and the integer you presented basically overflows the capacity of it." --- it does not. See the long discussion at https://stackoverflow.com/q/67222143/251311 It's not as simple. "and try to assume how JS would handle it." --- not need to do that, there is the ES2021 spec. – zerkms Apr 23 '21 at 00:46