1
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?

【JavaScript】parseInt() と Number()はどっちを使えばいいのか

Posted at

はじめに

学習中に文字列を数値に変換するときどっちがいいのかと言うところで悩んだので、違いをまとめてみた。

JavaScriptのデータ型について

inputのvuleの中身は文字列で返ってくることが多いです。また、データベースに値を送るときも数値で送らないといけないなどもあるでしょう。その際に文字列を数値に変換するとき使われるのがparseInt()Number()です。
どちらも文字列から数値に変換するものなので違いは何かを見てみましょう。

parseInt()について

まずはparseInt()です。
構文は以下です。

parseInt(string)
parseInt(string, radix)

radixには何進数から変換するかと言う意味です。基本は10進数になります。
また、以下のようスペースや文字が入っている場合でも、数値に変換してくれます。

console.log(parseInt("   123 "));// 123
parseInt("10abc"); // 10
parseInt("20px"); //  20

また少数などは切り捨てられます。

parseInt('12.34') // 12(小数点以下が切り捨てられる)

Number()について

次は、Number()です。
構文は以下です。

Number(value)

この関数は数値以外が入ってると、値を返してくれないです。

Number("20px"); // NaN
Number("10abc"); // NaN

少数も扱うことができます。

Number('12.34') // 12.34

どう使い分けるか

基本は Number()、parseInt() は “整数だけ欲しい/基数を指定して文字列を数える” ときがいいかなと言う結論です

おわりに

似たような関数があるとどっちが正解なのか悩みますね。

参考

https://blog.70-10.net/posts/parseint-and-number/
https://qiita.com/gp333/items/8bfa34979da64f15035c
https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Global_Objects/parseInt
https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Global_Objects/Number

1
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
1
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?