3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【TypeScript】文字列を数値へ変換する方法

Last updated at Posted at 2021-10-26

結論

  • 下記の関数を使用する
    • Number()
    • parseInt()
    • parseFloat()

Number()・parseInt()・parseFloat() の違い

Number()

.ts
Number('1'); // 1
Number('1.7'); // 1.7
Number('1px'); // NaN
Number('foo'); // NaN
Number(null); // 0

parseInt()

.ts
parseInt('1'); // 1
parseInt('1.7'); // 1
parseInt('1px'); // 1
parseInt('foo'); // NaN
parseInt(null); // NaN

parseFloat()

.ts
parseFloat('1'); // 1
parseFloat('1.7'); // 1.7
parseFloat('1.7px'); // 1.7
parseFloat('foo'); // NaN
parseFloat(null); // NaN

まとめ

解釈の仕方 小数点以下を変換するか null を渡した場合に返却する値
Number() 文字列全体を解釈する 変換する 0
parseInt() 文字列から数値部分を切り出す 切り捨てる NaN
parseFloat() 文字列から数値部分を切り出す 変換する NaN

※数値を文字列へ変換する方法は こちらの記事に記載

3
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?