正在分析字符串中的浮点值

Parsing floats from a string

本文关键字:字符串      更新时间:2023-09-26

我想解析数组的浮点数,如下所示:

var array = "-51.2132,0.3100";

我试过使用match(/'d+/g),但我想使用浮动

关于regex 的任何想法

提前感谢

此处不需要Regex。您可以首先通过,分割坐标以获得值,然后使用ParseFloat进行强制转换。试试这个:

var loc = "-51.2132,0.3100".split(',');
var lat = parseFloat(loc[0]); // = -51.2132
var lon = parseFloat(loc[1]); // = 0.31

试试这个:

var floats = array.split(',').map(function(e){return parseFloat(e)});
// result:
[-51.2132, 0.31]

这一行的作用:首先,将array拆分为逗号字符:

array.split(',') // ["-51.2132", "0.3100"]

然后,用parseFloat(item):替换该阵列中的每个item

["-51.2132", "0.3100"].map(function(e){ // For each item in the array
    return parseFloat(e); // Cast the current value to a float.
}); // [-51.2132, 0.31]
(-?'d+(?:'.'d+)?)

试试这个。抓住火柴。请参阅演示。

http://regex101.com/r/dZ1vT6/43

试试这个:

var array = "-51.2132,0.3100";
var regex = /-?'d+'.?'d*/g;
var items = array.match(regex);
var numbers = items.map(function (item) {
    return parseFloat(item);
});

http://regexr.com/39o6i