【问题标题】:Using parseFloat() or parseInt() and regex in JavaScript (converting a CSV file)在 JavaScript 中使用 parseFloat() 或 parseInt() 和正则表达式(转换 CSV 文件)
【发布时间】:2012-08-09 17:54:47
【问题描述】:

我正在将 CSV 文件转换为本地二维数组。我想知道是否有更好的方法将字符串转换为浮点数/整数,而不是使用正则表达式,然后使用 parseFloat()/parseInt。

想法/建议?

// numex() - checkes to see if the string (str) is a number
// returns number.valid (true||false) and number.value = (float||int||string)
numex = function(str){
  number = {};
  number.valid = false;
  number.value = str;
  // if we see a number then convert it to a floating point or integer
  if((number.value.search(/[^0-9^\.^\$^\%^\-^\"^,^ ]+/) < 0) && str.length > 0) {  
    number.valid = true;
    number.value = str.replace(/[^\-^0-9^\.]+/g, ''); // TODO add % coversion code for example if we see a 10% covert it to .1
    if(number.value.search(/[\.]/) >= 0) {  
       number.value = parseFloat(number.value); // replace floating point
    } else {
       number.value = parseInt(number.value); // replace integers
    }
  }
  return number; // number.valid = true or false;
}

var num = numex("1.101");
alert(num.value);

【问题讨论】:

    标签: javascript regex string floating-point integer


    【解决方案1】:

    我认为您根本不需要使用正则表达式。试试这个:

    var num = {};  
    num.value = new Number(str);  
    num.valid = !isNaN(num.value);
    

    数字构造函数比 parseInt 和 parseFloat 更严格,因为它不接受 10aaa1.2bbb 这样的字符串,因此无需执行正则表达式检查。

    【讨论】:

    • if(isNaN(value) || value == ""){return str;} else { return false; };
    【解决方案2】:

    我大大简化了代码,并使用了与 LeZuse 类似的东西。

    isNaN(值) ||值 == ""

    https://github.com/designpro/jCSV

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-23
      • 2018-10-31
      • 2011-10-02
      • 1970-01-01
      • 2019-05-11
      • 2023-03-09
      • 1970-01-01
      相关资源
      最近更新 更多