Why not login to Qiita and try out its useful features?

We'll deliver articles that match you.

You can read useful information later.

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?

WebフロントエンドAdvent Calendar 2024

Day 9

文字列を数値に変換するには。NumberとparseIntの使い分け

Posted at

文字列を数値に変換するには

JavaScriptで文字列'123'を数値123に変換したいときには、NumberparseIntを使用することで実現できます。
本記事では、両者の違いについてみていきます。

Number

Number()の引数には整数の他に、浮動小数点数を表す文字列も渡すことができ、数値型に変換してくれます1

引数に数値として解釈できない文字が含まれる場合にはNaNが返されますが、先頭と末尾の半角スペースや全角スペースなどの空白は無視してくれます。
数字の間に空白がある場合には無視されず、NaNが返されます。

console.log(Number('    123')) // 123
console.log(Number('     123.45 '))   // 123.45
console.log(Number('1234 5678'))   // NaN

また、Numberは10進数の場合にしか変換できない点がparseIntとは異なります。

parseInt

parseInt()によっても文字列を数値へ変換することができます。

parseInt()は名前にInt とあるように整数のみが解析対象です。
また、文字列を先頭から見ていったときに数値として認識されない文字が出てきた場合には、その文字以降が無視されます。
空白を除いた後、数値として認識されない文字が先頭に残る場合には、NaNが返されることとなります。

parseInt()は第2引数に基数を渡すことで、10進数以外で表現されている文字列を数値に変換することができます。
2進数から36進数までが指定可能です。

console.log(parseInt('   5  ')) // 5
console.log(parseInt('1.234'))  // 1
console.log(parseInt('234xyz')) // 234
console.log(parseInt('FE',16))  // 254
console.log(parseInt('FE',37))  // NaN

Numberと同様に先頭と末尾のスペースは無視されます。

parseIntでは浮動小数点数を扱えませんが、浮動小数点数を変換するためにparseFloatという関数も用意されています。

余談:<input>要素の入力を数値で取得

<input>要素では数字が入力されたとしても、valueプロパティからは文字列型として取得されます。

実はvalueのほかにvalueAsNumberというプロパティからも入力値を取得可能です。
valueAsNumberであれば、数値型として取得できます。
ただし、数値への変換ができない値が入力されていたときにはNaNが返されます。

  1. new Number()として呼び出すこともでき、ラッパーオブジェクトが得られますが、現在ではこの方法を使用する必要はないとされています。

0
0
1

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
axoloto210

@axoloto210(うぱ)

WebDeveloper Next.js React TypeScript User

Comments

knaief529
@knaief529

parseIntは、指数表記の数などを間違った値に変換してしまうので、単純に数値変換したい用途にはおすすめしません。
また、Numberよりも単項プラスのほうが簡単です。

const str = '12e-3';
console.log(parseInt(str)); // 12
console.log(Number(str)); // 12000
console.log(+str); // 12000
0

Let's comment your feelings that are more than good

Qiita Advent Calendar is held!

Qiita Advent Calendar is an article posting event where you post articles by filling a calendar 🎅

Some calendars come with gifts and some gifts are drawn from all calendars 👀

Please tie the article to your calendar and let's enjoy Christmas together!

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?

Login to continue?

Login or Sign up with social account

Login or Sign up with your email address