哪些数字可以安全地转换为 JavaScript 数字类型? [英] Which numbers can safely be converted into JavaScript numeric type?

查看:38
本文介绍了哪些数字可以安全地转换为 JavaScript 数字类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定一个发送小数点后 4 位或 6 位数字的后端,这些数字是否总是准确地转换为 JavaScript 数字类型(在 JSON 反序列化期间)?哪些数字会导致问题?

Given a backend that sends numbers with either 4 or 6 digits after the decimal point, will these numbers always be exactly converted to JavaScripts number type (during JSON deserialisation)? Which numbers will cause problems?

提示:假设后端是精确的,没有舍入错误等.但我需要了解前端可能会出现问题.

Hint: assume the backend is precise, no rounding errors etc. I need to understand at which point problems can occur on the frontend though.

推荐答案

Bergi 的评论:

JS(双精度浮点)数字的精度约为 16 位十进制数字.小数点前后有多少无所谓,两边都要算.所以只要你有 <=10 位数之前和 <= 6 位数之后,你会没事的.– 贝尔吉

JS (double-precision floating point) numbers have around 16 decimal digits of accuracy. How many of them are before or after the decimal point does not matter, you need to count both sides. So as long as you have <=10 digits before and <= 6 digits after the point, you'll be fine. – Bergi

然而,正如 Eric Postpischil 在 answer 中所说到一个相关的问题,说 doublefloat 格式有一些十进制数字是草率的术语".因为 doublefloat 通常对应于二进制数,而不是十进制数(更具体地说,分别是 IEEE 754 binary64 和 binary32),并且并非所有十进制数都可以转换为二进制没有损失的数字.

However, as Eric Postpischil remarked in an answer to a related question, saying that a double or float format has "some number of decimal digits is sloppy terminology". Because double and float typically correspond to numbers in binary, not decimal (more specifically, IEEE 754 binary64 and binary32, respectively), and not all decimal numbers can be converted to binary numbers without loss.

这篇关于哪些数字可以安全地转换为 JavaScript 数字类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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