toFixed() 和 toPrecision() 之间的区别?

发布于 2024-09-11 03:42:20 字数 194 浏览 1 评论 0 原文

我是 JavaScript 新手,刚刚发现了 toFixed()toPrecision() 来对数字进行舍入。但是,我无法弄清楚两者之间有什么区别。

number.toFixed()number.toPrecision() 之间有什么区别?

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.

What is the difference between number.toFixed() and number.toPrecision()?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(9

愛放△進行李 2024-09-18 03:42:20

toFixed(n) 提供小数点后的n长度; toPrecision(x) 提供 x 总长度。

参考 w3schools:toFixedtoPrecision

编辑
我不久前了解到 w3schools 并不是最好的来源,但我忘记了这个答案,直到我看到 kzh 的,呃,“热情”的评论。以下是来自 Mozilla 文档中心 针对 toFixed()toPrecision()。对我们所有人来说幸运的是,MDC 和 w3schools 在这一点上达成了一致。


为了完整起见,我应该提到 toFixed() 相当于 toFixed(0) ,而 toPrecision() 仅返回没有格式的原始数字。

当然,真正的事实来源是 JS 规范,在本例中是 https://tc39.es/ecma262/multipage/numbers-and-dates.html#sec-number.prototype.to precision

toFixed(n) provides n length after the decimal point; toPrecision(x) provides x total length.

Ref at w3schools: toFixed and 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 for toFixed() and for toPrecision(). Fortunately for all of us, MDC and w3schools agree with each other in this case.

For completeness, I should mention that toFixed() is equivalent to toFixed(0) and toPrecision() 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

要走就滚别墨迹 2024-09-18 03:42:20

我相信前者为您提供固定的小数位数,而后者为您提供固定的有效数字位数。

Math.PI.toFixed(2); // "3.14"
Math.PI.toPrecision(2); // "3.1"

此外,如果有更多整数数字,toPrecision 将产生科学记数法比指定精度的数字。

(Math.PI * 10).toPrecision(2); // "31"
(Math.PI * 100).toPrecision(2); // "3.1e+2"

编辑:
哦,如果您是 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.

Math.PI.toFixed(2); // "3.14"
Math.PI.toPrecision(2); // "3.1"

Furthermore, toPrecision will yield scientific notation if there are more integer digits in the number than the specified precision.

(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.

嘿咻 2024-09-18 03:42:20

例子说得很清楚:

var A = 123.456789;

// toFixed: argument operates on decimal
A.toFixed()      // 123
A.toFixed(-1)    // --- ERROR --- min = 0
A.toFixed(0)     // 123
A.toFixed(1)     // 123.5      round up last
A.toFixed(2)     // 123.46     round up last
A.toFixed(3)     // 123.457    round up last
A.toFixed(4)     // 123.4568   round up last
A.toFixed(5)     // 123.45679  round up last
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.toFixed(101)   // --- ERROR --- max = 100

// toPrecision: argument operates on entire number
A.toPrecision()      // 123.456789 
A.toPrecision(0)     // --- ERROR --- min = 1
A.toPrecision(1)     // 1e+2
A.toPrecision(2)     // 1.2e+2
A.toPrecision(3)     // 123
A.toPrecision(4)     // 123.5      round up last
A.toPrecision(5)     // 123.46     round up last
A.toPrecision(6)     // 123.457    round up last
A.toPrecision(7)     // 123.4568   round up last
A.toPrecision(8)     // 123.45679  round up last
A.toPrecision(9)     // 123.456789
A.toPrecision(10)    // 123.4567890
A.toPrecision(11)    // 123.45678900
A.toPrecision(101)   // --- ERROR --- max = 100

// ----------------------
// integer
// ----------------------
A = 12345;
A.toFixed(3)        // 12345.000  forces decimal digits
A.toPrecision(3)    // 1.23e+4    left-to-right truncate

// ----------------------
// edge-case rounding
// ----------------------
var B = 999.99;
B.toFixed(0)      // 1000
B.toFixed(1)      // 1000.0
B.toFixed(2)      // 999.99
B.toFixed(3)      // 999.990

B.toPrecision(0)  // --- ERROR ---- min = 1
B.toPrecision(1)  // 1e+3
B.toPrecision(2)  // 1.0e+3
B.toPrecision(3)  // 1.00e+3
B.toPrecision(4)  // 1000
B.toPrecision(5)  // 999.99
B.toPrecision(6)  // 999.990

var C = 0.99;
C.toFixed(0)      // 1
C.toFixed(1)      // 1.0
C.toFixed(2)      // 0.99
C.toFixed(3)      // 0.990

C.toPrecision(0)  // --- ERROR ---- min = 1
C.toPrecision(1)  // 1
C.toPrecision(2)  // 0.99
C.toPrecision(3)  // 0.990

// ----------------------
// edge-case integer
// ----------------------
var D = 999999;
D.toFixed(3)      // 999999.000
D.toPrecision(3)  // 1.00e+6

Examples speak clearly:

var A = 123.456789;

// toFixed: argument operates on decimal
A.toFixed()      // 123
A.toFixed(-1)    // --- ERROR --- min = 0
A.toFixed(0)     // 123
A.toFixed(1)     // 123.5      round up last
A.toFixed(2)     // 123.46     round up last
A.toFixed(3)     // 123.457    round up last
A.toFixed(4)     // 123.4568   round up last
A.toFixed(5)     // 123.45679  round up last
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.toFixed(101)   // --- ERROR --- max = 100

// toPrecision: argument operates on entire number
A.toPrecision()      // 123.456789 
A.toPrecision(0)     // --- ERROR --- min = 1
A.toPrecision(1)     // 1e+2
A.toPrecision(2)     // 1.2e+2
A.toPrecision(3)     // 123
A.toPrecision(4)     // 123.5      round up last
A.toPrecision(5)     // 123.46     round up last
A.toPrecision(6)     // 123.457    round up last
A.toPrecision(7)     // 123.4568   round up last
A.toPrecision(8)     // 123.45679  round up last
A.toPrecision(9)     // 123.456789
A.toPrecision(10)    // 123.4567890
A.toPrecision(11)    // 123.45678900
A.toPrecision(101)   // --- ERROR --- max = 100

// ----------------------
// integer
// ----------------------
A = 12345;
A.toFixed(3)        // 12345.000  forces decimal digits
A.toPrecision(3)    // 1.23e+4    left-to-right truncate

// ----------------------
// edge-case rounding
// ----------------------
var B = 999.99;
B.toFixed(0)      // 1000
B.toFixed(1)      // 1000.0
B.toFixed(2)      // 999.99
B.toFixed(3)      // 999.990

B.toPrecision(0)  // --- ERROR ---- min = 1
B.toPrecision(1)  // 1e+3
B.toPrecision(2)  // 1.0e+3
B.toPrecision(3)  // 1.00e+3
B.toPrecision(4)  // 1000
B.toPrecision(5)  // 999.99
B.toPrecision(6)  // 999.990

var C = 0.99;
C.toFixed(0)      // 1
C.toFixed(1)      // 1.0
C.toFixed(2)      // 0.99
C.toFixed(3)      // 0.990

C.toPrecision(0)  // --- ERROR ---- min = 1
C.toPrecision(1)  // 1
C.toPrecision(2)  // 0.99
C.toPrecision(3)  // 0.990

// ----------------------
// edge-case integer
// ----------------------
var D = 999999;
D.toFixed(3)      // 999999.000
D.toPrecision(3)  // 1.00e+6
当爱已成负担 2024-09-18 03:42:20

我认为最好用一个例子来回答这个问题。

假设您有以下数据:

var products = [
  {
    "title": "Really Nice Pen",
    "price": 150
  },
  {
    "title": "Golf Shirt",
    "price": 49.99
  },
  {
    "title": "My Car",
    "price": 1234.56
  }
]

您想要显示每个产品的标题和格式化价格。让我们首先尝试使用 toPrecision

document.write("The price of " + products[0].title + " is $" + products[0].price.toPrecision(5));

The price of Really Nice Pen is $150.00

看起来不错,所以您可能认为这也适用于其他产品:

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 $49.990
The price of My Car is $1234.6

不太好。我们可以通过更改每个产品的有效位数来解决此问题,但如果我们迭代产品数组,这可能会很棘手。让我们使用 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 $150.00
The price of Golf Shirt is $49.99
The price of My Car is $1234.56

这会产生您所期望的结果。不涉及猜测工作,也没有四舍五入。

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 toPrecision first:

document.write("The price of " + products[0].title + " is $" + products[0].price.toPrecision(5));

The price of Really Nice Pen is $150.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 $49.990
The price of My Car is $1234.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 toFixed instead:

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 $150.00
The price of Golf Shirt is $49.99
The price of My Car is $1234.56

This produces what you expected. There is no guess work involved, and there is no rounding.

请帮我爱他 2024-09-18 03:42:20

只是:

49.99.toFixed(5)
// → "49.99000"

49.99.toPrecision(5)
// → "49.990"

Just:

49.99.toFixed(5)
// → "49.99000"

49.99.toPrecision(5)
// → "49.990"
客…行舟 2024-09-18 03:42:20

在某些情况下,toPrecision() 将返回指数表示法,而 toFixed() 则不会。

Under certain circumstances, toPrecision() will return exponential notation, whereas toFixed() will not.

嗳卜坏 2024-09-18 03:42:20

toFixed(fractionDigits?) 在其他答案中已经或多或少准确地解释了:

  • fractionDigits [amount] 位数字的字符串表示形式:

它返回小数点 示例:

(-3).toFixed(1)     // '-3.0'
(-3).toFixed(0)     // '-3'
(-3).toFixed()      // '-3'
(-0.03).toFixed(1)  // '-0.0'

toPrecision( precision?) 在之前的答案中没有正确描述,所以应该注意。 另外我会添加一个免责声明,即我无法消化 toPrecision 上的规范,因此接下来的要点基于在 Node.js 中测试实现的尝试和错误方法。这些步骤并没有涵盖所有极端情况,例如如果数字为 NaN,或者精度 arg 不是整数,或者 <1 或 >100 等。这是为了不使解释像规范那样混乱。似乎是。

*案例编号通过列表保留,尽管案例可能看起来与其他案例相似,但它们需要展示特定行为

  1. 它首先代表指数表示法,精度是有效数字的位数,例如

情况 1:0.000004 → 精度 = 3 → 400 * 10^-8
情况 2:0.0000004 → 精度 = 3 → 400 * 10^-9
情况 3:123 → 精度 = 1 → 1.23 * 10^2
情况 4:153 → 精度 = 1 → 1.53 * 10^2
情况 5:1234.56 → 精度 = 3 → 123.456 * 10^1
情况 6:1234.56 → 精度 = 5 → 12345.6 * 10^-1

  1. 然后舍入有效数部分

情况 1:400 * 10^-8400 * 10^-8(不存在分数,没有变化)
情况 2:400 * 10^-9400 * 10^-9(与情况 1 的推理相同)
情况 3:1.23 * 10^21 * 10^21.23 舍入为 1)< br>
情况 4:1.53 * 10^22 * 10^21.53 四舍五入为 2
情况 5:123.456 * 10^1123 * 10^1(也四舍五入)
情况 6:12345.6 * 10^-112346 * 10^-1(四舍五入)

  1. 然后生成后面数字的字符串表示形式规则:

3a) 步骤 2 中有效数的所有数字都将被保留

3b) 如果精度 使用指数表示法 <小点之前的位数(“正常”,即十进制表示形式)

情况 3:1 * 10^2'1e+2'(数字现在为 100,3 位数字,精度为 1 ,使用指数)
情况 4:2 * 10^2'2e+2'(数字现在为 200,3 位数字,精度为 1,指数为使用)
情况 5:123 * 10^1'1.23e+3'(数字现在为 1230,4 位,精度为 3,指数使用;请注意,尾数已保留步骤 2 中的所有数字123 变为 1.23

3c) 指数如果数字具有 0 整数部分,并且小数点后面和第一个有效数字之前的零数量(以“正常”表示法)> 5,则使用表示法

情况2:400 * 10^-9'4.00e-7'(数字是0.0000004,它有0整数部分,并且小数点后有超过 5 个零,请注意, 400 * 10^-9 中的两个零被保留)< /p>

3d ) 如果数字的整数部分为 0 并且小数点后面的零个数 <= 5,则使用十进制表示法,但将保留步骤 2 中有效数的数字

情况1:400 * 10^-8'0.00000400'(有效数字部分的两个零已被保留)

3e) 十进制表示法如果精度 >=十进制表示中的点之前的位数,则使用

情况6:12346 * 10^-11234.6(步骤2中的数字的十进制形式为1234.6,精度为5,前面的位数小数点为 4,字符串使用小数表示法,步骤 2 中有效数的所有数字均被保留)

console.log((0.000004).toPrecision(3));
console.log((0.0000004).toPrecision(3));
console.log((123).toPrecision(1));
console.log((153).toPrecision(1));
console.log((1234.56).toPrecision(3));
console.log((1234.56).toPrecision(5));

toFixed(fractionDigits?) has been explained more or less accurately in other answers:

  • it returns a string representation of the number with fractionDigits [amount] digits after the decimal point:

An example:

(-3).toFixed(1)     // '-3.0'
(-3).toFixed(0)     // '-3'
(-3).toFixed()      // '-3'
(-0.03).toFixed(1)  // '-0.0'

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 on toPrecision, 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

  1. it first represents the number in exponential notation with precision being the number of digits in the significand, like

Case 1: 0.000004 → precision = 3 → 400 * 10^-8
Case 2: 0.0000004 → precision = 3 → 400 * 10^-9
Case 3: 123 → precision = 1 → 1.23 * 10^2
Case 4: 153 → precision = 1 → 1.53 * 10^2
Case 5: 1234.56 → precision = 3 → 123.456 * 10^1
Case 6: 1234.56 → precision = 5 → 12345.6 * 10^-1

  1. then it rounds the significand part

Case 1: 400 * 10^-8400 * 10^-8 (no fraction was present, no change)
Case 2: 400 * 10^-9400 * 10^-9 (same reasoning as in case 1)
Case 3: 1.23 * 10^21 * 10^2 (1.23 was rounded to 1)
Case 4: 1.53 * 10^22 * 10^2 (1.53 rounded to 2)
Case 5: 123.456 * 10^1123 * 10^1 (rounded too)
Case 6: 12345.6 * 10^-112346 * 10^-1 (rounded)

  1. then it produces a string representation of the number following the rules:

3a) 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)

Case 3: 1 * 10^2'1e+2' (number is now 100, 3 digits, precision is 1, exponent is used)
Case 4:2 * 10^2'2e+2' (number is now 200, 3 digits, precision is 1, exponent is used)
Case 5:123 * 10^1'1.23e+3' (number is now 1230, 4 digits, precision is 3, exponent is used; note that the significand has preserved all digits from step 2: 123 became 1.23)

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

Case 2: 400 * 10^-9'4.00e-7' (number is 0.0000004, it has the 0 integer part and there are >5 zeros after the decimal point, note that the two zeros from 400 * 10^-9 were preserved)

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

Case 1: 400 * 10^-8'0.00000400' (the two zeros from the significand part have been preserved)

3e) Decimal notation is used, if precision >= the number of digits before the point in decimal representation

Case 6: 12346 * 10^-11234.6 (the decimal form of the number in step 2 is 1234.6, precision is 5, number of digits before the decimal point is 4, the string uses decimal notation, all digits from the significand in step 2 were preserved)

console.log((0.000004).toPrecision(3));
console.log((0.0000004).toPrecision(3));
console.log((123).toPrecision(1));
console.log((153).toPrecision(1));
console.log((1234.56).toPrecision(3));
console.log((1234.56).toPrecision(5));

﹏半生如梦愿梦如真 2024-09-18 03:42:20

例如,我们将变量 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

凌乱心跳 2024-09-18 03:42:20

toPrecision()toFixed() 都是设计用于在打印数字之前对其进行格式化的函数。因此它们都返回 String 值。

有一个例外。如果您对负数数字文字使用这些函数,由于运算符优先级,将返回一个数字。这意味着 toFixed()toPrecision() 将首先返回一个字符串,然后 - 减号运算符会将字符串转换回来为负值的数字。请参阅下面的示例。

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() 返回一个 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"

由于运算符优先级,在负数字文字上使用这些函数将返回数字而不是字符串。以下是一些示例:

// 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

有趣的事实:从 -0.0456.toFixed(1) 可以看出,有符号零

请参阅:+0 和 -0 相同吗?

Both toPrecision() and toFixed() are functions designed to format a number before printing it out. So they both return String 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() 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.

toPrecision() returns a String 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.

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 String representing the Number object in fixed-point notation, rounded up. This function only cares about the decimal point numbers

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)

See: Are +0 and -0 the same?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文