TIL 010 JavaScript_String to Number & Number to String

Alice KimΒ·2021λ…„ 3μ›” 18일
0

TIL

λͺ©λ‘ 보기
10/23
post-thumbnail

🎯Datatype을 λ°”κΎΈλŠ” 방법을 μ΅ν˜€λ³΄μž


πŸ”‘λ°©λ²•1. μžλ™ν˜• λ³€ν™˜ 이용

1. From Number to String

let data = 100;
console.log(`Data Type: ${typeof data}`) //"Data Type: number"

data += '';
console.log(`Data Type: ${typeof data}`) //"Data Type: string"

2. From String to Number

let data = "100";
console.log(`Data Type: ${typeof data}`) //"Data Type: string"

data *= 1;
console.log(`Data Type: ${typeof data}`) //"Data Type: number"

* μž₯점: κ°€μž₯ κ°„λ‹¨ν•˜κ²Œ λ³€ν™˜ μ‹œν‚¬ 수 μžˆλ‹€.

* 단점: 타인이 보면 μ–΄λ–€ μ˜λ„λ‘œ μž‘μ„±ν•œ μ½”λ“œμΈμ§€ μ§κ΄€μ μœΌλ‘œ μ•ŒκΈ° μ–΄λ €μšΈ 수 μžˆλ‹€.

πŸ”‘λ°©λ²•2. λ‚΄μž₯ν•¨μˆ˜ 이용1

1. From Number to String

let data = 100;
console.log(`Data Type: ${typeof data}`) //"Data Type: number"

data = String(data);
console.log(`Data Type: ${typeof data}`) //"Data Type: string"

2. From String to Number

let data = "100";
console.log(`Data Type: ${typeof data}`) //"Data Type: string"

data = Number(data);
console.log(`Data Type: ${typeof data}`) //"Data Type: number"

* μž₯점: νƒ€μž… μ „ν™˜μ΄ λͺ…μ‹œμ μ΄λ‹€.

πŸ”‘λ°©λ²•3. λ‚΄μž₯ν•¨μˆ˜ 이용2

1. From Number to String

let data = 100;
console.log(`Data Type: ${typeof data}`) //"Data Type: number"

data = toString(data);
console.log(`Data Type: ${typeof data}`) //"Data Type: string"

2. From String to Number

let data = "100";
console.log(`Data Type: ${typeof data}`) //"Data Type: string"

data = parseInt(data);
console.log(`Data Type: ${typeof data}`) //"Data Type: number"

* 주의!

  • parseInt() ν•¨μˆ˜λŠ” ν˜•λ³€ν™˜ μžμ²΄κ°€ λͺ©μ μ΄ μ•„λ‹ˆλ‹€.
  • parseInt() ν•¨μˆ˜λŠ” λ¬Έμžμ—΄ 인자λ₯Ό ꡬ문 λΆ„μ„ν•˜μ—¬ νŠΉμ • μ§„μˆ˜μ˜ μ •μˆ˜λ₯Ό λ°˜ν™˜ν•œλ‹€.

πŸ‘€ μ°Έκ³ ν•  자료
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt

profile
If you don't build your dream, someone will hire you to help build theirs.

0개의 λŒ“κΈ€