toFixed功能不正常(请给出一个不能替代的理由) [英] toFixed function not working properly ( please give a reason not an alternative)

查看:151
本文介绍了toFixed功能不正常(请给出一个不能替代的理由)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

toFixed()函数对浮点值的响应不同。
例如:

toFixed() function responding differently for float values. For Example:

 var a = 2.555;
 var b = 5.555;

console.log(a.toFixed(2));  /* output is 2.56 */ 
console.log(b.toFixed(2));  /* output is 5.55 */

对于2.555 / 3.555,结果为(2.56 / 3.56)

For 2.555/3.555 results are (2.56/3.56)

对于其他值(不确定所有值),它显示#.55(#表示任何数字)

For other values(not sure for all values) it is showing #.55 (# refers to any number)

我很困惑任何人都可以帮助我。

I am confused can any one help me out.

提前致谢。

推荐答案

Javascript使用二进制浮点数字表示(IEEE754)。
使用此表示形式,唯一可以精确表示的数字形式为n / 2 m ,其中 n m 是整数。

Javascript uses a binary floating point representation for numbers (IEEE754). Using this representation the only numbers that can be represented exactly are in the form n/2m where both n and m are integers.

任何不合理的数字,如果分母是2的整数幂,则无法准确表示因为在二进制中它是一个周期数(它在点之后有无限的二进制数字)。

Any number that is not a rational where the denominator is an integral power of two is impossible to represent exactly because in binary it is a periodic number (it has infinite binary digits after the point).

数字 0.5 (即1/2)很好,(二进制只是 0.1 2 )但是例如 0.55 (即11/20)无法准确表示(二进制中 0.1000110011001100112 ... 0.10(0011)2 ,最后一部分 0011 2 重复无限次)。

The number 0.5 (i.e. 1/2) is fine, (in binary is just 0.1₂) but for example 0.55 (i.e. 11/20) cannot be represented exactly (in binary it's 0.100011001100110011₂… i.e. 0.10(0011)₂ with the last part 0011₂ repeating infinite times).

如果您需要进行任何结果取决于精确十进制数的计算,您需要使用精确的十进制表示。如果小数位数是固定的(例如3),则一个简单的解决方案是将所有值保持为整数乘以1000 ...

If you need to do any computation in which the result depends on exact decimal numbers you need to use an exact decimal representation. A simple solution if the number of decimals is fixed (e.g. 3) is to keep all values as integers by multiplying them by 1000...

2.555 --> 2555
5.555 --> 5555
3.7   --> 3700

并相应地进行乘法和除法时调整计算(例如,在乘以两个数后需要除以结果由1000)。

and adjusting your computation when doing multiplications and divisions accordingly (e.g. after multiplying two numbers you need to divide the result by 1000).

IEEE754双精度格式准确,整数高达9,007,199,254,740,992,这对于价格/价值来说通常已经足够了(四舍五入最常见的情况)一个问题)。

The IEEE754 double-precision format is accurate with integers up to 9,007,199,254,740,992 and this is often enough for prices/values (where the rounding is most often an issue).

这篇关于toFixed功能不正常(请给出一个不能替代的理由)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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