如何在 JavaScript 中舍入一个数字?.toFixed() 返回一个字符串? [英] How can I round a number in JavaScript? .toFixed() returns a string?

查看:22
本文介绍了如何在 JavaScript 中舍入一个数字?.toFixed() 返回一个字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在这里遗漏了什么吗?

Am I missing something here?

var someNumber = 123.456;
someNumber = someNumber.toFixed(2);
alert(typeof(someNumber));
//alerts string

为什么 .toFixed() 返回一个字符串?

我想将数字四舍五入为 2 位十进制数字.

I want to round the number to 2 decimal digits.

推荐答案

它返回一个字符串,因为 0.1 及其幂(用于显示小数)不能用二进制表示(至少不能完全准确地表示)浮点系统.

It returns a string because 0.1, and powers thereof (which are used to display decimal fractions), are not representable (at least not with full accuracy) in binary floating-point systems.

例如,0.1 真的是 0.1000000000000000055511151231257827021181583404541015625,0.01 真的是 0.01000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000之间0之间都分别(感谢 BigDecimal 证明我的观点.:-P)

For example, 0.1 is really 0.1000000000000000055511151231257827021181583404541015625, and 0.01 is really 0.01000000000000000020816681711721685132943093776702880859375. (Thanks to BigDecimal for proving my point. :-P)

因此(没有十进制浮点数或有理数类型),将其作为字符串输出是将其精确修剪为显示所需精度的唯一方法.

Therefore (absent a decimal floating point or rational number type), outputting it as a string is the only way to get it trimmed to exactly the precision required for display.

这篇关于如何在 JavaScript 中舍入一个数字?.toFixed() 返回一个字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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