Javascript toFixed() 和 toPrecision() 的区别?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3337849/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Difference between toFixed() and toPrecision()?
提问by Jessica
I'm new to JavaScript and just discovered toFixed()and toPrecision()to round numbers. However, I can't figure out what the difference between the two is.
我是 JavaScript 的新手,刚刚发现toFixed()并toPrecision()四舍五入。但是,我无法弄清楚两者之间的区别是什么。
What is the difference between number.toFixed()and number.toPrecision()?
number.toFixed()和 和有number.toPrecision()什么区别?
回答by Pops
toFixed(n)provides nlength after the decimal point; toPrecision(x)provides xtotal length.
toFixed(n)提供n小数点后的长度;toPrecision(x)提供x总长度。
Ref at w3schools: toFixedand toPrecision
参考 w3schools:toFixed和toPrecision
EDIT:
I learned a while back that w3schools isn't exactly the best source, but I forgot about this answer until I saw kzh's, uh, "enthusiastic" comment. Here are additional refs from Mozilla Doc Center fortoFixed()and fortoPrecision(). Fortunately for all of us, MDC and w3schools agree with each other in this case.
编辑:
我不久前了解到 w3schools 并不是最好的来源,但是直到我看到 kzh 的“热情”评论之前,我才忘记了这个答案。下面是从Mozilla的文档中心额外裁判的toFixed()和为toPrecision()。对我们所有人来说幸运的是,在这种情况下,MDC 和 w3schools 彼此同意。
For completeness, I should mention that toFixed()is equivalent to toFixed(0)and toPrecision()just returns the original number with no formatting.
为了完整起见,我应该提到它toFixed()等效于toFixed(0)并且toPrecision()只返回没有格式的原始数字。
回答by Tom
I believe that the former gives you a fixed number of decimal places, whereas the latter gives you a fixed number of significant digits.
我相信前者为您提供固定的小数位数,而后者为您提供固定数量的有效数字。
Math.PI.toFixed(2); // "3.14"
Math.PI.toPrecision(2); // "3.1"
Furthermore, toPrecisionwill yield scientific notationif there are more integer digits in the number than the specified precision.
此外,如果数字中的整数位数多于指定的精度,toPrecision则将产生科学记数法。
(Math.PI * 10).toPrecision(2); // "31"
(Math.PI * 100).toPrecision(2); // "3.1e+2"
EDIT: Oh, and if you are new to JavaScript, I can highly recommend the book "JavaScript: The Good Parts" by Douglas Crockford.
编辑:哦,如果您是 JavaScript 新手,我强烈推荐Douglas Crockford所著的“ JavaScript: The Good Parts”一书。
回答by bob
Examples speak clearly:
例子说得很清楚:
var A = 123.456789;
A.toFixed() // 123
A.toFixed(0) // 123
A.toFixed(1) // 123.5
A.toFixed(2) // 123.46
A.toFixed(3) // 123.457
A.toFixed(4) // 123.4568
A.toFixed(5) // 123.45679
A.toFixed(6) // 123.456789
A.toFixed(7) // 123.4567890
A.toFixed(8) // 123.45678900
A.toFixed(9) // 123.456789000
A.toFixed(10) // 123.4567890000
A.toFixed(11) // 123.45678900000
A.toPrecision() // 123.456789
A.toPrecision(0) // --- ERROR ---
A.toPrecision(1) // 1e+2
A.toPrecision(2) // 1.2e+2
A.toPrecision(3) // 123
A.toPrecision(4) // 123.5
A.toPrecision(5) // 123.46
A.toPrecision(6) // 123.457
A.toPrecision(7) // 123.4568
A.toPrecision(8) // 123.45679
A.toPrecision(9) // 123.456789
A.toPrecision(10) // 123.4567890
A.toPrecision(11) // 123.45678900
回答by Big McLargeHuge
I think this is best answered with an example.
我认为这最好用一个例子来回答。
Let's say you have the following data:
假设您有以下数据:
var products = [
{
"title": "Really Nice Pen",
"price": 150
},
{
"title": "Golf Shirt",
"price": 49.99
},
{
"title": "My Car",
"price": 1234.56
}
]
You want to display each of these products with the title and formatted price. Let's try using toPrecisionfirst:
您希望显示带有标题和格式化价格的每个产品。让我们toPrecision先尝试使用:
document.write("The price of " + products[0].title + " is $" + products[0].price.toPrecision(5));
The price of Really Nice Pen is 0.00
Looks good, so you might think this will work for the other products as well:
看起来不错,所以您可能认为这也适用于其他产品:
document.write("The price of " + products[1].title + " is $" + products[2].price.toPrecision(5));
document.write("The price of " + products[2].title + " is $" + products[2].price.toPrecision(5));
The price of Golf Shirt is .990
The price of My Car is 34.6
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 toFixedinstead:
不太好。我们可以通过更改每个产品的有效数字位数来解决这个问题,但是如果我们迭代产品的数组可能会很棘手。让我们toFixed改用:
document.write("The price of " + products[0].title + " is $" + products[0].price.toFixed(2));
document.write("The price of " + products[1].title + " is $" + products[2].price.toFixed(2));
document.write("The price of " + products[2].title + " is $" + products[2].price.toFixed(2));
The price of Really Nice Pen is 0.00
The price of Golf Shirt is .99
The price of My Car is 34.56
This produces what you expected. There is no guess work involved, and there is no rounding.
这产生了你所期望的。不涉及猜测工作,也没有四舍五入。
回答by Alexander Mextner
Just:
只是:
49.99.toFixed(5)
// → "49.99000"
49.99.toPrecision(5)
// → "49.990"
回答by Robusto
Under certain circumstances, toPrecision()will return exponential notation, whereas toFixed()will not.
在某些情况下,toPrecision()将返回指数符号,而toFixed()不会。
回答by Sathish Kumar.S Shankaran
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
例如,我们考虑变量a为,var a = 123.45 a.toPrecision(6) 输出为123.450 a.toFixed(6) 输出如123.450000 //小数点后6位
回答by philip yoo
Both toPrecision()and toFixed()are functions designed to format a number before printing it out. So they both return Stringvalues.
双方toPrecision()并toFixed()都设计打印出来之前格式的数字功能。所以它们都返回String值。
There is one exception. If you use these functions on a negativeNumber literal, due to operator precedence, a Number is returned. What this means is that toFixed()or toPrecision()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.
有一个例外。如果您在负数文字上使用这些函数,由于运算符优先级,将返回一个数字。这意味着toFixed()ortoPrecision()将首先返回一个字符串,然后-减号运算符会将字符串转换回数字作为负值。请参阅下面的示例。
toPrecision()returns a Stringrepresenting 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.
toPrecision()返回以String定点或指数表示法表示的 Number 对象,四舍五入为有效数字。因此,如果您指定精度为 1,它会返回第一个有效数字以及科学记数法以指示 10 的幂,或者如果有效数字 < 0,则返回其小数点前的前一个 0。
const num1 = 123.4567;
// if no arguments are passed, it is similar to converting the Number to String
num1.toPrecision(); // returns "123.4567
// scientific notation is used when you pass precision count less than total
// number of digits left of the period
num1.toPrecision(2); // returns "1.2e+2"
// last digit is rounded if precision is less than total significant digits
num1.toPrecision(4); // returns "123.5"
num1.toPrecision(5); // returns "123.46"
const largeNum = 456.789;
largeNum.toPrecision(2); // returns "4.6e+2"
// trailing zeroes are added if precision is > total digits of the number or float
num1.toPrecision(9); // returns "123.456700"
const num2 = 123;
num2.toPrecision(4); // returns "123.0"
const num3 = 0.00123;
num3.toPrecision(4); // returns "0.001230"
num3.toPrecision(5); // returns "0.0012300"
// if the number is < 1, precision is by the significant digits
num3.toPrecision(1); // returns "0.001"
toFixed()returns a Stringrepresenting the Number object in fixed-point notation, rounded up. This function only cares about the decimal point numbers
toFixed()返回以String定点表示法表示的 Number 对象,四舍五入。该函数只关心小数点数字
const num1 = 123.4567;
// if no argument is passed, the fractions are removed
num1.toFixed(); // returns "123"
// specifying an argument means you the amount of numbers after the decimal point
num1.toFixed(1); // returns "123.5"
num1.toFixed(3); // returns "123.457"
num1.toFixed(5); // returns "123.45670"
num1.toFixed(7); // returns "123.4567000"
// trying to operator on number literals
2.34.toFixed(1); // returns "2.3"
2.toFixed(1); // returns SyntaxError
(2).toFixed(1); // returns "2.0"
(2.34e+5).toFixed(1); // returns "234000.0"
I 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:
我在上面提到了一个例外,由于运算符优先级,在负数文字上使用这些函数将返回数字而不是字符串。这里有些例子:
// Note: these are returning as Number
// toPrecision()
-123.45.toPrecision(); // returns -123.45
-123.45.toPrecision(2); // returns -120
-123.45.toPrecision(4); // returns -123.5
-2.34e+2.toPrecision(1); // returns -200
-0.0456.toPrecision(1); // returns -0.05
-0.0456.toPrecision(6); // returns -0.0456
// toFixed()
-123.45.toFixed(); // returns -123.45
-123.45.toFixed(1); // returns -123.5
-123.45.toFixed(4); // returns -123.45
-0.0456.toFixed(1); // returns -0
-0.0456.toFixed(6); // -0.0456
Fun fact: there are signed zeroes as seen from -0.0456.toFixed(1)
有趣的事实:从图中可以看出有符号零 -0.0456.toFixed(1)
请参阅:+0 和 -0 相同吗?

