javascript:解析开始和结束都带有字符串前缀的float

javascript : parse float with string prefix in both start and end

本文关键字:字符串 前缀 float 结束 开始 javascript      更新时间:2023-09-26

如何将此字符串转换为float?我想要结果900.50

案例1:var convertThis = 'any string here 900,50 also any string here';

案例2:var convertThis = 'any string here 900.50 also any string here';

如何做到这一点?

尝试以下代码:

var text = 'any string here 900,50 also any string here';
var matched = text.match(/'d+[,.]'d+/)[0].replace(',', '.');
var num = parseFloat(matched, 10);
console.log(matched);
console.log(num);

打印:

900.50
900.5

您可以这样做:

var num = parseFloat(convertThis.replace(/[^'d'.,]/g,'').replace(/,/,'.'));

但要注意,一旦你的文本中有多个数字或点,就会出现这种情况。如果你想要一些可靠的东西,你需要更精确地确定字符串是什么

假设你想从更复杂的字符串中提取所有数字,你可以进行

var numbers = convertThis.split(/'s/).map(function(s){
    return parseFloat(s.replace(',','.'))
 }).filter(function(v) { return v });

在这里,您将获得[900.5]

var myFloat = +(convertThis.match(/'d+[,'.]?'d+/)[0].replace(",","."))