Front/JS & jQuery

[JS] 숫자를 문자로 변환하기

오선지♬ 2022. 5. 21. 20:15
728x90
반응형

1. toString()

- ().toString(2) => 2진수로 변환 , default로 ()이면 10진수로 변환.

const str1 = (123.1).toString();
const str2 = (123).toString();
const str3 = (3).toString(2);

document.write(str1 + ', ' + typeof str1 + '<br>');		// 123.1, string
document.write(str2 + ', ' + typeof str2 + '<br>');		// 123, string
document.write(str3 + ', ' + typeof str3 + '<br>');		// 11, string


2. String()

const str1 = String(123.1);
const str2 = String(123);

document.write(str1 + ', ' + typeof str1 + '<br>');		// 123.1, string
document.write(str2 + ', ' + typeof str2 + '<br>');		// 123, string

 

 

3. Template String (템플릿 문자열)

 

- ES6 문법인 Template String(템플릿 문자열)을 이용해서 숫자를 문자열로 변환

템플릿 문자열은 백틱( ` )으로 문자열을 감싸서 표현하고,

(백틱은 작은 따옴표가 아닌, 키보드 왼쪽 상단의 '~'키 아래에 있는 key.)

'${}' 안에 Javascript 변수를 넣으면 해당 변수의 값을 대응시켜서 문자열을 만들어 준다.

const number1 = 123.1;
const number2 = 123;
const str1 = `${number1}`;
const str2 = `${number2}`;

document.write(str1 + ', ' + typeof str1 + '<br>');		// 123.1, string
document.write(str2 + ', ' + typeof str2 + '<br>');		// 123, string

 

4. 빈 문자열 이어붙이기

const str1 = 123.1 + "";
const str2 = 123 + "";

document.write(str1 + ', ' + typeof str1 + '<br>');		// 123.1, string
document.write(str2 + ', ' + typeof str2 + '<br>');		// 123, string

 

 

출처 : https://hianna.tistory.com/491

728x90
반응형