toFixed() 和 toPrecision() 之间的区别?
我是 JavaScript 新手,刚刚发现了 toFixed()
和 toPrecision()
来对数字进行舍入。但是,我无法弄清楚两者之间有什么区别。
number.toFixed()
和 number.toPrecision()
之间有什么区别?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(9)
toFixed(n)
提供小数点后的n
长度;toPrecision(x)
提供x
总长度。参考 w3schools:toFixed 和 toPrecision
为了完整起见,我应该提到
toFixed()
相当于toFixed(0)
,而toPrecision()
仅返回没有格式的原始数字。当然,真正的事实来源是 JS 规范,在本例中是 https://tc39.es/ecma262/multipage/numbers-and-dates.html#sec-number.prototype.to precision
toFixed(n)
providesn
length after the decimal point;toPrecision(x)
providesx
total length.Ref at w3schools: toFixed and toPrecision
For completeness, I should mention that
toFixed()
is equivalent totoFixed(0)
andtoPrecision()
just returns the original number with no formatting.And of course, the real source of truth is the JS specification, which in this case is https://tc39.es/ecma262/multipage/numbers-and-dates.html#sec-number.prototype.toprecision
我相信前者为您提供固定的小数位数,而后者为您提供固定的有效数字位数。
此外,如果有更多整数数字,
toPrecision
将产生科学记数法比指定精度的数字。编辑:
哦,如果您是 JavaScript 新手,我强烈推荐这本书“JavaScript: The Good部分”作者:Douglas Crockford。
I believe that the former gives you a fixed number of decimal places, whereas the latter gives you a fixed number of significant digits.
Furthermore,
toPrecision
will yield scientific notation if there are more integer digits in the number than the specified precision.EDIT:
Oh, and if you are new to JavaScript, I can highly recommend the book "JavaScript: The Good Parts" by Douglas Crockford.
例子说得很清楚:
Examples speak clearly:
我认为最好用一个例子来回答这个问题。
假设您有以下数据:
您想要显示每个产品的标题和格式化价格。让我们首先尝试使用
toPrecision
:看起来不错,所以您可能认为这也适用于其他产品:
不太好。我们可以通过更改每个产品的有效位数来解决此问题,但如果我们迭代产品数组,这可能会很棘手。让我们使用
toFixed
来代替:这会产生您所期望的结果。不涉及猜测工作,也没有四舍五入。
I think this is best answered with an example.
Let's say you have the following data:
You want to display each of these products with the title and formatted price. Let's try using
toPrecision
first:Looks good, so you might think this will work for the other products as well:
Not so good. We can fix this by changing the number of significant digits for each product, but if we're iterating over the array of products that could be tricky. Let's use
toFixed
instead:This produces what you expected. There is no guess work involved, and there is no rounding.
只是:
Just:
在某些情况下,
toPrecision()
将返回指数表示法,而toFixed()
则不会。Under certain circumstances,
toPrecision()
will return exponential notation, whereastoFixed()
will not.toFixed(fractionDigits?)
在其他答案中已经或多或少准确地解释了:fractionDigits
[amount] 位数字的字符串表示形式:它返回小数点 示例:
toPrecision( precision?)
在之前的答案中没有正确描述,所以应该注意。 另外我会添加一个免责声明,即我无法消化toPrecision
上的规范,因此接下来的要点基于在 Node.js 中测试实现的尝试和错误方法。这些步骤并没有涵盖所有极端情况,例如如果数字为 NaN,或者精度 arg 不是整数,或者 <1 或 >100 等。这是为了不使解释像规范那样混乱。似乎是。*案例编号通过列表保留,尽管案例可能看起来与其他案例相似,但它们需要展示特定行为
精度
是有效数字的位数,例如3a) 步骤 2 中有效数的所有数字都将被保留
3b) 如果
精度
使用指数表示法
<小点之前的位数(“正常”,即十进制表示形式)3c) 指数如果数字具有 0 整数部分,并且小数点后面和第一个有效数字之前的零数量(以“正常”表示法)> 5,则使用表示法
3d ) 如果数字的整数部分为 0 并且小数点后面的零个数 <= 5,则使用十进制表示法,但将保留步骤 2 中有效数的数字
3e) 十进制表示法如果
精度
>=十进制表示中的点之前的位数,则使用toFixed(fractionDigits?)
has been explained more or less accurately in other answers:fractionDigits
[amount] digits after the decimal point:An example:
toPrecision(precision?)
has not been described correctly in the previous answers, so one should pay attention. Also I'd add a disclaimer, that I haven't been able to digest the spec ontoPrecision
, so the next points are based on the try and error approach of testing the implementation in Node.js. And these steps don't cover all corner cases like what if the number is NaN, or the precision arg is not integer, or is <1 or >100 etc. This is in order not to make the explanation cluttered as the spec seems to be.*Numbering of cases is preserved thru the list, despite cases may seem similar to other, they are required to demonstrate a particular behavior
precision
being the number of digits in the significand, like3a) all digits from the significand in step 2 will be preserved
3b) Exponential notation is used if
precision
< the number of digits before the point (in 'normal', i.e. decimal representation)3c) Exponential notation is used if the number has the 0 integer part and the number of zeros right after the decimal point and before the first significant digit (in 'normal' notation) is >5
3d) Decimal notation is used, if the number has the 0 integer part and the number of zeros right after the decimal point <= 5 but the digits from the significand from step 2 will be preserved
3e) Decimal notation is used, if
precision
>= the number of digits before the point in decimal representation例如,我们将变量 a 视为:
变量 a = 123.45
a.toPrecision(6)
输出为 123.450
a. 固定(6)
输出类似于 123.450000 // 小数点后 6 位
For example , we consider the variable a as,
var a = 123.45
a.toPrecision(6)
The output is 123.450
a.toFixed(6)
The output is like 123.450000 // 6 digits after decimal point
toPrecision()
和toFixed()
都是设计用于在打印数字之前对其进行格式化的函数。因此它们都返回 String 值。有一个例外。如果您对负数数字文字使用这些函数,由于运算符优先级,将返回一个数字。这意味着
toFixed()
或toPrecision()
将首先返回一个字符串,然后-
减号运算符会将字符串转换回来为负值的数字。请参阅下面的示例。toPrecision()
返回一个String
,以定点或四舍五入到有效数字的指数表示法表示 Number 对象。因此,如果您指定想要精度为 1,它将返回第一个有效数字以及表示 10 次方的科学记数法,或者如果有效数字 < 则返回小数点前的前一个 0。 0.toFixed()
返回一个String
,以定点表示法表示 Number 对象,并向上舍入。该函数只关心我上面提到的小数点数字,但由于运算符优先级,在负数字文字上使用这些函数将返回数字而不是字符串。以下是一些示例:
有趣的事实:从
-0.0456.toFixed(1)
可以看出,有符号零请参阅:+0 和 -0 相同吗?
Both
toPrecision()
andtoFixed()
are functions designed to format a number before printing it out. So they both returnString
values.There is one exception. If you use these functions on a negative Number literal, due to operator precedence, a Number is returned. What this means is that
toFixed()
ortoPrecision()
will return a string first, and then the-
minus operator will convert the string back to a Number as a negative value. Please see below for an example.toPrecision()
returns aString
representing the Number object in fixed-point or exponential notation rounded to significant digits. So if you specify that you want a precision of 1, it returns the first significant number along with either scientific notation to indicate the powers of 10 or the previous 0's before its decimal point if the significant number is < 0.toFixed()
returns aString
representing the Number object in fixed-point notation, rounded up. This function only cares about the decimal point numbersI mentioned above an exception where using these functions on negative Number literals will return a Number and not a String due to operator precedence. Here are some examples:
Fun fact: there are signed zeroes as seen from
-0.0456.toFixed(1)
See: Are +0 and -0 the same?