LoginSignup
0
1

More than 1 year has passed since last update.

fetchなどでダブルクオーテーション囲みの数値が入ってきた場合の対処方法

Posted at

問題

fetchで返されるレスポンスに"123"などのダブルクオーテーションが付いた数値が帰ってくる。
APIドキュメント上は、数値と定義されているが、””囲みなので実際の演算時や.toFixedしたい場合などに文字型となりエラーとなる。

数値であることはAPIドキュメント上、保証されているとき、どうすれば簡単に数値型へ変えられるか。

対応

単項プラスを使う。

const numericString = "10";
const numericValue = 10;

// 通常は文字列結合
console.log(`numericString + numericValue: ${numericString + numericValue}`);

// 単項プラスをあらかじめすることで
console.log(`+numericString + numericValue: ${+numericString + numericValue}`);
[LOG]: "numericString + numericValue: 1010" 
[LOG]: "+numericString + numericValue: 20" 
0
1
2

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
1