当我想从“Sometext 330”这样的字符串中“parseInt或parseFloat”时,我总是有一个“NaN”
Var a = "Sometext 330"
return parseFloat(a);
它将返回“NaN”,但我需要整数或 float 330
最佳答案
您可以先清理字符串,以便在解析数字之前字符串中仅保留数字。
edit: now it's even safer as it will accept Number types without blowing up.
var a = "Sometext 330"
function safeParseFloat(val) {
return parseFloat(isNaN(val) ? val.replace(/[^\d\.]+/g, '') : val)
}
function superSafeParseFloat(val) {
if (isNaN(val)) {
if ((val = val.match(/([0-9\.,]+\d)/g))) {
val = val[0].replace(/[^\d\.]+/g, '')
}
}
return parseFloat(val)
}
console.log(
safeParseFloat(a),
safeParseFloat(2000.69)
)
console.log(
superSafeParseFloat('blah $2,000,000.69 AUD'),
superSafeParseFloat('blah $8008 USD'),
superSafeParseFloat('NotANumber'),
superSafeParseFloat(8008.69),
superSafeParseFloat('... something 500.5... test')
)
关于javascript - parseFloat() 从字符串的中间开始,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40803585/