program tip

toFixed ()와 toPrecision ()의 차이점은 무엇입니까?

radiobox 2020. 7. 27. 07:47
반응형

toFixed ()와 toPrecision ()의 차이점은 무엇입니까?


저는 JavaScript를 처음 사용하고 방금 발견 toFixed()하고 toPrecision()숫자를 반올림했습니다. 그러나 두 가지의 차이점이 무엇인지 알 수 없습니다.

차이점은 무엇이며 number.toFixed()그리고 number.toPrecision()?


toFixed(n)n소수점 뒤의 길이를 제공합니다 . 전체 길이를 toPrecision(x)제공합니다 x.

참고 W3 스쿨에서 : 에서는 toFixed에서는 toPrecision

편집 :
나는 w3schools가 최고의 소스가 아니라는 것을 얼마 동안 배웠지 만 kzh의 "열정적"댓글을 볼 때 까지이 대답을 잊었습니다. 여기에 모질라 문서 센터에서 추가 심판 있습니다 에 대한toFixed()대한이toPrecision() . 다행스럽게도이 경우 MDC와 w3schools는 서로 동의합니다.

완성도를 위해, 나는 그 언급해야한다 toFixed()과 동일 toFixed(0)하고 toPrecision()단지 형식이없는 원래 수를 반환합니다.


전자는 소수점 이하 자릿수를 제공하는 반면 후자는 소수점 이하 자릿수를 제공한다고 믿습니다.

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를 처음 사용 하는 경우 Douglas Crockford " JavaScript : The Good Parts " 책을 강력히 추천 할 수 있습니다 .


나는 이것이 가장 좋은 예라고 생각합니다.

다음과 같은 데이터가 있다고 가정 해 봅시다.

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

이것은 당신이 기대 한 것을 만들어냅니다. 추측 작업이 없으며 반올림이 없습니다.


예를 들어 명확하게 말하십시오.

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

다만:

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

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

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


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

참고URL : https://stackoverflow.com/questions/3337849/difference-between-tofixed-and-toprecision

반응형