Math.trunc()
Baseline
Widely available
This feature is well established and works across many devices and browser versions. Itโs been available across browsers since โจ2015๋ 7์โฉ.
Math.trunc()
์ ์ ๋ฉ์๋๋ ์ซ์์ ์์ ๋ถ๋ถ์ ์ ๊ฑฐํ ์ซ์์ ์ ์ ๋ถ๋ถ์ ๋ฐํํฉ๋๋ค.
์๋ํด ๋ณด๊ธฐ
console.log(Math.trunc(13.37));
// Expected output: 13
console.log(Math.trunc(42.84));
// Expected output: 42
console.log(Math.trunc(0.123));
// Expected output: 0
console.log(Math.trunc(-0.123));
// Expected output: -0
๊ตฌ๋ฌธ
Math.trunc(x)
๋งค๊ฐ๋ณ์
x
-
์ซ์
๋ฐํ ๊ฐ
x
์ ์ ์ ๋ถ๋ถ
์ค๋ช
๋ค๋ฅธ ์ธ ๊ฐ์ง Math
๋ฉ์๋์ธ Math.floor()
, Math.ceil()
๋ฐ Math.round()
์ ๋ฌ๋ฆฌ, Math.trunc()
์ ์๋ ๋ฐฉ์์ ๋งค์ฐ ๊ฐ๋จํฉ๋๋ค. ์ด ๋ฉ์๋๋ ์ธ์๊ฐ ์์์ด๋ ์์์ด๋ ์๊ด์์ด ์์์ ๊ณผ ๊ทธ ์ค๋ฅธ์ชฝ์ ์ซ์๋ค์ ์ ๋จํฉ๋๋ค(์๋ผ๋
๋๋ค).
trunc()
๋ Math
์ ์ ์ ๋ฉ์๋์ด๊ธฐ ๋๋ฌธ์, ์์ฑํ Math
๊ฐ์ฒด์ ๋ฉ์๋๋ก ์ฌ์ฉํ๋ ๊ฒ์ด ์๋๋ผ ํญ์ Math.trunc()
๋ก ์ฌ์ฉํฉ๋๋ค (Math
๋ ์์ฑ์๊ฐ ์๋๋๋ค).
์์
Math.trunc() ์ฌ์ฉํ๊ธฐ
Math.trunc(-Infinity); // -Infinity
Math.trunc("-1.123"); // -1
Math.trunc(-0.123); // -0
Math.trunc(-0); // -0
Math.trunc(0); // 0
Math.trunc(0.123); // 0
Math.trunc(13.37); // 13
Math.trunc(42.84); // 42
Math.trunc(Infinity); // Infinity
๋นํธ ์ฐ์ฐ no-ops์ ์ฌ์ฉํ์ฌ ์ซ์ ์๋ผ๋ด๊ธฐ
๊ฒฝ๊ณ :
๋ฌด์ํ ์ ์๋ ๊ฒฝ๊ณ ์กฐ๊ฑด ๋๋ฌธ์ Math.trunc()
์ ํด๋ฆฌํ์ด ์๋๋๋ค.
๋นํธ ์ฐ์ฐ์ ํผ์ฐ์ฐ์๋ฅผ 32๋นํธ ์ ์๋ก ๋ณํํ๋๋ฐ, ์ด๋ฅผ ์ด์ฉํด ์ญ์ฌ์ ์ผ๋ก ๋ถ๋์์์ ์ซ์๋ฅผ ์ ๋จํ๋ ๋ฐ ํ์ฉํด ์์ต๋๋ค. ์ผ๋ฐ์ ์ธ ๊ธฐ์ ๋ค์ ๋ค์๊ณผ ๊ฐ์ต๋๋ค.
const original = 3.14;
const truncated1 = ~~original; // ์ด์ค ๋ถ์
const truncated2 = original & -1; // -1๊ณผ์ AND ๋นํธ ์ฐ์ฐ
const truncated3 = original | 0; // 0๊ณผ์ OR ๋นํธ ์ฐ์ฐ
const truncated4 = original ^ 0; // 0๊ณผ์ XOR ๋นํธ ์ฐ์ฐ
const truncated5 = original >> 0; // 0๋งํผ ๋นํธ ์ํํธ
์ฃผ์ํ ์ ์ ์ด๋ ๋ณธ์ง์ ์ผ๋ก toInt32
์ ๊ฐ์ง๋ง Math.trunc
์ ๊ฐ์ง ์๋๋ ์ ์
๋๋ค. ๊ฐ์ด -231 - 1 < value
< 231 (-2147483649 < value
< 2147483648) ๋ฒ์๋ฅผ ๋ฒ์ด๋ ๊ฒฝ์ฐ, ๋ณํ ์ ์ค๋ฒํ๋ก์ฐ๊ฐ ๋ฐ์ํ ์ ์์ต๋๋ค.
const a = ~~2147483648; // -2147483648
const b = ~~-2147483649; // 2147483647
const c = ~~4294967296; // 0
~~
๋ฅผ Math.trunc()
๋์ ์ฌ์ฉํ ๋๋ ์
๋ ฅ ๋ฒ์๊ฐ 32๋นํธ ์ ์์ ๋ฒ์ ๋ด์ ์๋ค๊ณ ํ์ ํ ๋๋ง ์ฌ์ฉํ์ธ์.
๋ช ์ธ์
Specification |
---|
ECMAScriptยฎ 2026 Language Specification # sec-math.trunc |
๋ธ๋ผ์ฐ์ ํธํ์ฑ
Loadingโฆ