0
0

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.

[JavaScript] '+'で数字に型変換する

Last updated at Posted at 2021-04-02

概要

文字列→数字だったり日付→数字などに型変換する場合にNumber(), parseInt(), parseFloat()が使えますが、
+を使うことで型変換できることを知ったのでメモします。

実装

.js
const hoge = '123'
console.log(+hoge);

//結果:123

しかし、文字が入る場合はキャストできなくなります。

.js
const str = '123abc'
console.log(+str)
//結果:NaN
console.log(parseFloat(str))
//結果:123

文字が入る可能性がある場合は明示的にした方がよさそうです。

関係ないけど

ちなみに明示的に型変換する場合、文字を全て無視すると思っていたのですが
最初の文字までの数値しか読まれないみたいです。
また一つ賢くなりました。

.js
const str = '1.53a2a3a'
console.log(parseFloat(str))
//結果:1.53
0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?