Code개발일지
[JS] Number 타입을 String 타입으로 변환// toString(), String(), num+'',Template String ${(num)}
Minhhk
2022. 10. 25. 00:54
1. toString()으로 숫자를 문자열로 변환
toString() 메소드를 사용하여 숫자를 문자열로 변환할 수 있습니다.
const num = 5;
const str1 = num.toString();
const str2 = (100).toString();
const str3 = (-10.11).toString();
console.log(num + ', ' + typeof num);
console.log(str1 + ', ' + typeof str1);
console.log(str2 + ', ' + typeof str2);
console.log(str3 + ', ' + typeof str3);
Output:
5, number
5, string
100, string
-10.11, string
2. String()으로 숫자를 문자열로 변환
String() 메소드를 사용하여 숫자를 문자열로 변환할 수 있습니다.
const num = 5;
const str1 = String(num);
const str2 = String(100);
const str3 = String(-10.11);
console.log(num + ', ' + typeof num);
console.log(str1 + ', ' + typeof str1);
console.log(str2 + ', ' + typeof str2);
console.log(str3 + ', ' + typeof str3);
Output:
5, number
5, string
100, string
-10.11, string
3. 빈 문자열을 붙여서 숫자를 문자열로 변환
다음과 같이 Number 객체에 빈 문자열을 붙이면 String 객체로 변환됩니다.
const num = 5;
const str1 = num + '';
const str2 = 100 + '';
const str3 = -10.11 + '';
console.log(num + ', ' + typeof num);
console.log(str1 + ', ' + typeof str1);
console.log(str2 + ', ' + typeof str2);
console.log(str3 + ', ' + typeof str3);
Output:
5, number
5, string
100, string
-10.11, string
4. Template String으로 숫자를 문자열로 변환
ES6의 Template String을 사용하여 아래와 같이 Number를 문자열로 변환할 수 있습니다.
const num = 5;
const str1 = `${num}`;
const str2 = `${100}`;
const str3 = `${-10.11}`;
console.log(num + ', ' + typeof num);
console.log(str1 + ', ' + typeof str1);
console.log(str2 + ', ' + typeof str2);
console.log(str3 + ', ' + typeof str3);
Output:
5, number
5, string
100, string
-10.11, string
5. toFixed()로 숫자를 문자열로 변환
아래와 같이 toFixed()로 숫자를 문자열로 변환할 수 있습니다.
toFixed()는 toFixed(0)과 같으며, toFixed(n)은 소수점 n + 1 자리에서 반올림하고 n자리까지만 문자열로 변환합니다.
let num = 5.3;
const str1 = num.toFixed()
const str2 = (100.6666).toFixed()
const str3 = (100.1234).toFixed(1);
const str4 = (100.1234).toFixed(3);
console.log(num + ', ' + typeof num);
console.log(str1 + ', ' + typeof str1);
console.log(str2 + ', ' + typeof str2);
console.log(str3 + ', ' + typeof str3);
console.log(str4 + ', ' + typeof str4);
Output:
5.3, number
5, string
101, string
100.1, string
100.123, string
References