在golang中复制javascript不安全数字 [英] replicate javascript unsafe numbers in golang

查看:56
本文介绍了在golang中复制javascript不安全数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我进行了一个计算,得出了"5726718050568503296".在JS中,它给出的是"5726718050568503000"

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

我想在go中复制这种行为

I would like to replicate this behavior in go

推荐答案

为什么在JS中将5726718050568503296截断的原因正如其他人所提到的,这是由 toString()在JavaScript中实现的方式引起的,该方式似乎使用最小位数的有效数字来返回相同的表示数字,而不是通过数学方式返回最接近的数字.但是,您可以使用特殊的 -1 精度和 strconv.FormatFloat :

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

游乐场链接: https://play.golang.org/p/9ZObcB3so4o

这篇关于在golang中复制javascript不安全数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆