toFixed

number.toFixed

toFixed() λ©”μ„œλ“œλŠ” 숫자λ₯Ό κ³ μ • μ†Œμˆ˜μ  ν‘œκΈ°λ²•μœΌλ‘œ ν‘œκΈ°ν•΄ λ°˜ν™˜ν•œλ‹€.

function financial(x) {
  return Number.parseFloat(x).toFixed(2);
}

financial(123.456); // "123.46"
financial(0.004); // "0.00"
financial('1.23e+5'); // "123000.00"

Syntax

numObj.toFixed([digits])

Parameters

digits (Optional)

μ†Œμˆ˜μ  뒀에 ν‘œμ‹œλ˜λŠ” μžλ¦Ώμˆ˜μ΄λ‹€. 0 이상 20 μ΄ν•˜μ˜ 값을 μ‚¬μš©ν•  수 있으며, κ΅¬ν˜„μ²΄μ— 따라 더 넓은 λ²”μœ„μ˜ 값을 지원할 μˆ˜λ„ μžˆλ‹€. 값을 μ§€μ •ν•˜μ§€ μ•ŠμœΌλ©΄ 0을 μ‚¬μš©ν•œλ‹€.

Return value

κ³ μ • μ†Œμˆ˜μ  ν‘œκΈ°λ²•μ„ μ‚¬μš©ν•˜μ—¬ μ£Όμ–΄μ§„ 숫자λ₯Ό λ‚˜νƒ€λ‚΄λŠ” λ¬Έμžμ—΄μ΄λ‹€.

Exceptions

RangeError

digits κ°€ λ„ˆλ¬΄ μž‘κ±°λ‚˜ λ„ˆλ¬΄ 클 λ•Œ, 값이 0κ³Ό 100 μ‚¬μ΄μ˜ 값이라면 RangeError κ°€ λ°œμƒν•˜μ§€ μ•ŠλŠ”λ‹€. κ΅¬ν˜„μ²΄μ— 따라 더 ν¬κ±°λ‚˜ μž‘μ€ 값을 지원할 수 μžˆλ‹€.

TypeError

Number κ°€ μ•„λ‹Œ κ°μ²΄μ—μ„œ ν˜ΈμΆœν•œ 경우

Description

toFixed() λŠ” μ§€μˆ˜ ν‘œκΈ°λ²•μ„ μ‚¬μš©ν•˜μ§€ μ•ŠλŠ”λ‹€. μ†Œμˆ˜μžλ¦¬ 뒀에 μ •ν™•ν•œ 자릿수λ₯Ό digits 만큼 λ‚˜νƒ€λ‚Έ numObj λ¬Έμžμ—΄ ν‘œν˜„μ„ λ°˜ν™˜ν•œλ‹€. ν•„μš”μ— 따라 μˆ˜μΉ˜λŠ” 반올림된 μ†Œμˆ˜ 뢀뢄을 μ§€μ •λœ 길이가 λ˜λ„λ‘ ν•„μš”μ— λ”°λΌμ„œ 0으둜 μ±„μ›Œμ§„λ‹€. numObj κ°€ 1e+21 보닀 큰 경우, 이 λ©”μ„œλ“œλŠ” λ‹¨μˆœνžˆ Number.prototype.toString() 을 ν˜ΈμΆœν•˜μ—¬ 받은 μ§€μˆ˜ ν‘œκΈ°λ²• κ²°κ³Όλ₯Ό λŒ€μ‹  λ°˜ν™˜ν•œλ‹€.

κ²½κ³ : 뢀동 μ†Œμˆ˜μ  μˆ˜λŠ” λͺ¨λ“  μ†Œμˆ˜λ₯Ό μ •ν™•ν•˜κ²Œ μ΄μ§„μˆ˜λ‘œ λ‚˜νƒ€λ‚Ό 수 μ—†λ‹€. 이둜 인해 0.1 + 0.2 === 0.3 이 false 같은 예기치 μ•Šμ€ κ²°κ³Όκ°€ λ°œμƒν•  수 μžˆλ‹€.

Examples

toFixed μ‚¬μš©

const numObj = 12345.6789;

numObj.toFixed(); // "12346" λ°˜μ˜¬λ¦Όν•˜λ©°, μ†Œμˆ˜ 뢀뢄이 μ—†λŠ” 점을 μœ μ˜ν•˜μž
numObj.toFixed(1); // '12345.7' λ°˜μ˜¬λ¦Όν•œλ‹€.
numObj.toFixed(6); // "12345.678900" λΉˆκ³΅κ°„μ„ 0으둜 μ±„μš΄λ‹€.
(1.23e+20).toFixed(2); // "123000000000000000000.00"
(1.23e-10).toFixed(2); // "0.00"
2.34.toFixed(1);  // "2.3"
2.35.toFixed(1); // "2.4" λ°˜μ˜¬λ¦Όν•œλ‹€.
2.55.toFixed(1); // "2.5" 🧐
-2.34.toFixed(1); // -2.3 (μ—°μ‚°μž μš°μ„  μˆœμœ„μ΄κΈ° λ•Œλ¬Έμ—, 음수의 경우 λ¬Έμžμ—΄μ„ λ°˜ν™˜ν•˜μ§€ μ•ŠλŠ”λ‹€) 였 ""κ°€ μ—†λ‹€.
(-2.34).toFixed(1); // "-2.3" κ΄„ν˜Έλ₯Ό μ‚¬μš©ν•  경우 λ¬Έμžμ—΄μ„ λ°˜ν™˜ν•œλ‹€.

Last updated

Was this helpful?