簡體   English   中英

在javascript中將字符串轉換為整數或浮點數

[英]Convert string to either integer or float in javascript

如果我不知道變量是類似整數還是類似小數,是否有一種直接的方法可以將字符串解析為整數或浮點數?

a = '2'; // => parse to integer
b = '2.1'; // => parse to float
c = '2.0'; // => parse to float
d = 'text'; // => don't parse

編輯:似乎我的問題缺乏必要的上下文:我想在不丟失原始格式的情況下進行一些計算(原始格式因此表示整數與浮點數。我不關心原始小數位數):

例子:

String containing the formatted number ('2') => parse to number (2.0) => do some calculations (2.0 + 1 = 3.0) => restore "original format" ('3' and not '3.0')

如果輸入是 2.0,則想要的結果將是“3.0”(而不是“3”)。

將具有數字數據的字符串乘以 1。您將獲得數字數據值。

var int_value = "string" * 1;

在你的情況下

a = '2' * 1; // => parse to integer
b = '2.1' * 1; // => parse to float
c = '2.0' * 1; // => parse to float
d = 'text' * 1; // => don't parse    //NaN value

對於最后一個,您將獲得NaN值。 手動處理 NaN 值

只需將其包裝在Number()

Number('123') === 123

Number('-123.456') === -123.456

我就是這樣最終解決的。 除了將變量類型添加到變量之外,我沒有找到任何其他解決方案......

 var obj = { a: '2', b: '2.1', c: '2.0', d: 'text' }; // Explicitly remember the variable type for (key in obj) { var value = obj[key], type; if ( isNaN(value) || value === "" ) { type = "string"; } else { if (value.indexOf(".") === -1) { type = "integer"; } else { type = "float"; } value = +value; // Convert string to number } obj[key] = { value: value, type: type }; } document.write("<pre>" + JSON.stringify(obj, 0, 4) + "</pre>");

您可以使用:

function parse(x){
  return x==x*1?x*1:x
 }

 function parse(x){ return x==x*1?x*1:x } console.log(parse(1),typeof parse(1)) console.log(parse("1"),typeof parse("1")) console.log(parse("1.1"),typeof parse("1.1")) console.log(parse("1A"),typeof parse("1A"))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM