在 JavaScript 中使用 parseFloat() 或 parseInt() 和正则表达式(转换 CSV 文件)

Using parseFloat() or parseInt() and regex in JavaScript (converting a CSV file)

本文关键字:正则表达式 转换 CSV 文件 parseInt parseFloat JavaScript      更新时间:2023-09-26

我正在将CSV文件转换为本地2D数组。 我想知道是否有更好的方法将字符串转换为 floats/int,而不是使用正则表达式,然后是 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);

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

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

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

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

isNaN(值) || 值 == "

https://github.com/designpro/jCSV