답변:
toFixed(n)n소수점 이하 길이를 제공합니다 . 총 길이를 toPrecision(x)제공합니다 x.
w3schools 참조 : toFixed 및 toPrecision
편집 :
나는 w3schools가 정확히 최고의 소스가 아니라는 것을 잠시 배웠지 만 kzh의 "열정적 인"코멘트를 볼 때 까지이 대답을 잊어 버렸습니다. 여기에 모질라 문서 센터에서 추가 심판 있습니다 에 대한toFixed()및 대한이toPrecision(). 다행스럽게도 MDC와 w3schools는이 경우에 서로 동의합니다.
완성도를 위해, 나는 그 언급해야한다 toFixed()과 동일 toFixed(0)하고 toPrecision()단지 형식이없는 원래 수를 반환합니다.
toPrecision(x)" x전체 길이를 제공"하지 않고 주어진 유효 자릿수로 형식을 지정합니다. 예를 들어, 0.0000022.toPrecision(1)반환합니다 0.000002.
toPrecision(x)는 x전체 길이를 제공합니다 ." 반드시 유지되는 것은 아닙니다. 카운터 예 :0.00001234.toPrecision(3)
전자는 고정 된 소수 자릿수를 제공하고 후자는 고정 된 유효 자릿수를 제공한다고 생각합니다.
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 = 999999999999999934464;, a.toFixed(0)반환 "1e+21". 아마도 더 정확한 대답은 toFixed ()가 toString ()이하지 않는 한 지수 표기법을 반환하지 않는다는 것입니다.
예를 들어, 변수 a를 as, var a = 123.45 a.toPrecision (6) 출력은 123.450 a.toFixed (6) 출력은 123.450000 // 소수점 뒤 6 자리와 같습니다.
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이 있습니다. -0.0456.toFixed(1)
참조 : +0과 -0은 같은가요?