Number.prototype.toString()
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์โฉ.
toString() ๋ฉ์๋๋ ํน์ ํ Number ๊ฐ์ฒด๋ฅผ ๋ํ๋ด๋ ๋ฌธ์์ด์ ๋ฐํํฉ๋๋ค.
์๋ํด ๋ณด๊ธฐ
function hexColour(c) {
if (c < 256) {
return Math.abs(c).toString(16);
}
return 0;
}
console.log(hexColour(233));
// Expected output: "e9"
console.log(hexColour("11"));
// Expected output: "b"
๊ตฌ๋ฌธ
numObj.toString([radix]);
๋งค๊ฐ๋ณ์
radixOptional-
์์ ๊ฐ์ ๋ํ๋ด๊ธฐ ์ํด ์ฌ์ฉ๋๊ธฐ ์ํ ๊ธฐ์ค์ ์ ํ๋ 2์ 36์ฌ์ด์ ์ ์. (์ง์๋ฅผ ๋ํ๋ด๋ ๊ธฐ์์ ๊ฐ.)
๋ฐํ ๊ฐ
Number ๊ฐ์ฒด๋ฅผ ๋ช
์ํ๋ ๋ฌธ์์ด.
์์ธ
RangeError-
๋ง์ฝ
toString()์2์36์ ์ฌ์ ๊ฐ์ด ์๋radix๊ฐ ์ฃผ์ด์ง๋ฉด,RangeError์๋ฌ๊ฐ ๋ฐ์ํฉ๋๋ค.
์ค๋ช
Number ๊ฐ์ฒด๋ Object ๊ฐ์ฒด์ toString()๋ฉ์๋๋ฅผ ์ค๋ฒ๋ผ์ด๋ฉํ๋ฉฐ, Object.prototype.toString() ๋ฅผ ์์๋ฐ์ง ์์ต๋๋ค. Number ๊ฐ์ฒด์์ toString() ๋ฉ์๋๋ ํน์ ์ง์๋ก ๊ฐ์ฒด๋ฅผ ํํํ ๋ฌธ์์ด์ ํ์ํฉ๋๋ค.
toString() ๋ฉ์๋๋ ๋ฉ์๋์ ์ฒซ ๋ฒ์งธ ์๊ท๋จผํธ๋ฅผ ํ์ฑํ์ฌ, ๋ฉ์๋๋ ํน์ ๊ธฐ์(radix)๋ฅผ ๊ธฐ์ค์ผ๋ก ํ ์ง์ ๊ฐ์ ๋ฌธ์์ด์ ํ์ํ๊ธฐ ์ํ ์๋๋ฅผ ํฉ๋๋ค. ์ง์๋ฅผ ๋ํ๋ด๋ ๊ธฐ์ ๊ฐ(radix) ์ด 10 ์ด์์ ๊ฐ์ผ ๋๋, ์ํ๋ฒณ์ ๊ธ์๋ 9๋ณด๋ค ํฐ ์๋ฅผ ๋ํ๋
๋๋ค. ์๋ฅผ ๋ค๋ฉด, 16์ง์(base 16)๋, ์ํ๋ฒณ f ๊น์ง ์ฌ์ฉํ์ฌ ํํ๋ฉ๋๋ค.
๋ง์ฝ์ radix๊ฐ ์ด ์ง์ ๋์ง ์์ผ๋ฉด, ์์๋ก 10์ง์๋ก ๊ฐ์ ํ๊ฒ ๋ฉ๋๋ค.
๋, numObj๊ฐ ์์๋ผ๋ฉด, - ๋ถํธ๋ ์ ์ง๋ฉ๋๋ค. ์ด๋ ๊ธฐ์(radix) ๊ฐ์ด 2์ผ ๊ฒฝ์ฐ์๋ผ๋ ์ ์ฉ๋ฉ๋๋ค. ๋ฆฌํด๋ ๋ฌธ์์ด์ - ๋ถํธ๊ฐ ์์ ์๋ numObj ์ ์์ 2์ง์ ํ์์ด์ง, numObj์ ๋ ๊ฐ์ ์กฐํฉ์ด ์๋๊ธฐ ๋๋ฌธ์
๋๋ค.
numObj ๊ฐ ์ ์๊ฐ ์๋๋ฉด, ์ (.) ๋ถํธ๋ ์์ ์๋ฆฌ์ ๋ถ๋ฆฌํ๊ธฐ ์ํด ์ฌ์ฉ๋ฉ๋๋ค.
์์
>toString ์ฌ์ฉ
var count = 10;
console.log(count.toString()); // displays '10'
console.log((17).toString()); // displays '17'
console.log((17.2).toString()); // displays '17.2'
var x = 6;
console.log(x.toString(2)); // displays '110'
console.log((254).toString(16)); // displays 'fe'
console.log((-10).toString(2)); // displays '-1010'
console.log((-0xff).toString(2)); // displays '-11111111'
๋ช ์ธ
| Specification |
|---|
| ECMAScriptยฎ 2026 Languageย Specification> # sec-number.prototype.tostring> |