programing

고정()과 고정() 사이의 차이?

oldcodes 2023. 9. 26. 22:31
반응형

고정()과 고정() 사이의 차이?

는 자바스크립트를 접했고 전에 를 발견했습니다.toFixed()그리고.toPrecision()어림잡아 는 그 둘의 하지만 저는 그 둘의 차이점이 무엇인지 알 수가 없습니다.

입니까의 입니까?number.toFixed()그리고.number.toPrecision()?

toFixed(n)공을 합니다.n이;toPrecision(x)공을 합니다.x

3개 학교의 Refaction: 고정고정으로

편집:
얼마 전에 w3 schools가 정확히 최고의 정보원은 아니라는 것을 알게 되었지만, kzh의 "열정적인" 코멘트를 보기 전까지 이 답변을 잊어버렸습니다.다음은 에 대한 Mozilla Doc Center의 추가 참조입니다. 다행히도 우리 모두에게 MDC와 w3 학교는 이 경우에 서로 동의합니다.

저는 , .toFixed()입니다에 합니다.toFixed(0)그리고.toPrecision()형식 지정 없이 원래 번호만 반환합니다.

그리고 물론 진실의 진정한 원천은 JS 사양이며, 이 경우 https://tc39.es/ecma262/multipage/numbers-and-dates.html#sec-number.prototype.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"

편집: 아, 그리고 자바스크립트를 처음 접하신다면 "자바스크립트: 더글러스 크록포드의 "The Good Parts".

예를 들어 다음과 같이 명확히 알 수 있습니다.

var A = 123.456789;

A.toFixed()      // 123
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.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      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

// ----------------------
// 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 ----
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 ----
C.toPrecision(1)  // 1
C.toPrecision(2)  // 0.99
C.toPrecision(3)  // 0.990

저는 이것이 예를 들어 가장 잘 대답할 수 있다고 생각합니다.

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

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()stoFixed()하지 않을 것이다.

toFixed(fractionDigits?)는 다른 되었습니다.

  • 를 문자열을 합니다.fractionDigits소수점 뒤의 [금액]

예:

(-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.0000043→ = 3→400 * 10^-8
례 2:0.00000043→ = 3→400 * 10^-9
례 3:1231→ = 1→1.23 * 10^2
례 4:1531→ = 1→1.53 * 10^2
례 5:1234.563→ = 3→123.456 * 10^1
례 6:1234.565→ = 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^2(1.23로 반올림되었습니다.1)
례 4:1.53 * 10^22 * 10^2(1.53한으로 2)
례 5:123.456 * 10^1123 * 10^1도)
례 6:12345.6 * 10^-112346 * 10^-1(rounded)

  1. 그런 다음 규칙을 따르는 숫자의 문자열 표현을 생성합니다.

3a) 2단계에서 부호의 모든 숫자가 보존됩니다.

3b) 다음과 같은 경우 지수 표기법을 사용합니다.precision점) <규',현)

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단계부터 모든 숫자를 보존합니다.123e1.23)

3c) 지수 표기법은 소수점 바로 뒤에 숫자가 0의 정수 부분과 0의 숫자를 가지고 있고 첫 번째 유효숫자('정규' 표기에서)가 5를 초과하는 경우에 사용됩니다.

2:400 * 10^-9'4.00e-7'(숫자는 0.0000004이며, 다음을 포함합니다.0정수 부분과 소수점 뒤에 5개 이상의 0이 있습니다. 두의 0은 다음과 같습니다. 400 * 10^-9 보존)

3d) 소수점 <= 5> 바로 뒤에 숫자가 0의 정수 부분과 0의 숫자를 갖지만 2단계부터 숫자가 보존되는 경우 10진 표기법을 사용합니다.

1:400 * 10^-8'0.00000400'에서 두 의 0되었습니다).

3e) 다음과 같은 경우 10진 표기법을 사용합니다.precision에서 점 =

6:12346 * 10^-11234.6(는 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));

예를 들어 변수 a를 vara = 123.45 a. to Precision(6) 출력 123.450 a. to Fixed(6) 소수점 뒤의 출력 123.450000 // 6자리와 같습니다.

둘다요.toPrecision()그리고.toFixed()숫자를 출력하기 전에 형식을 지정하도록 설계된 함수입니다. 다 돌아갔군요String가치.

한 가지 예외가 있습니다.연산자 우선 순위로 인해 음수 리터럴에서 이러한 함수를 사용할 경우 번호가 반환됩니다.이것이 의미하는 것은toFixed()아니면toPrecision() 끈을 하고,-빼기 연산자는 문자열을 음수 값으로 다시 변환합니다.예를 들어 아래를 참조하시기 바랍니다.

toPrecision()품 a를 합니다.String숫자 개체를 의미 있는 숫자로 반올림한 고정 소수점 또는 지수 표기법으로 나타냅니다.따라서 정밀도를 1로 지정할 경우 유의한 수가 0일 경우 과학적 표기법과 함께 첫 번째 유의한 수를 반환하여 소수점 앞에 10 또는 이전 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()품 a를 합니다.StringNumber 개체를 반올림한 고정 소수점 표기법으로 나타냅니다.다 을 씁니다.

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이 같습니까?

언급URL : https://stackoverflow.com/questions/3337849/difference-between-tofixed-and-toprecision

반응형