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

查看:183
本文介绍了如何在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.01000000000000000020816681711721685132943093776702880859375。 (感谢 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天全站免登陆