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

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

number.toFixed()과 의 차이점은 무엇입니까 number.toPrecision()?



답변

toFixed(n)n소수점 이하 길이를 제공합니다 . 총 길이를 toPrecision(x)제공합니다 x.

w3schools 참조 : toFixedtoPrecision

편집 :
나는 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"

편집 : 오, 그리고 만약 당신이 자바 스크립트를 처음 접 한다면 Douglas Crockford 의 책 ” JavaScript : The Good Parts “를 강력히 추천 할 수 있습니다 .


답변

예는 명확하게 말합니다.

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


답변

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

다음 데이터가 있다고 가정 해 보겠습니다.

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

이것은 당신이 기대 한 것을 생산합니다. 관련된 추측 작업이 없으며 반올림도 없습니다.


답변

다만:

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

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


답변

특정 상황에서는 toPrecision()지수 표기법을 반환하지만 toFixed()그렇지 않습니다.


답변

예를 들어, 변수 a를 as, var a = 123.45 a.toPrecision (6) 출력은 123.450 a.toFixed (6) 출력은 123.450000 // 소수점 뒤 6 자리와 같습니다.