I always have a “NaN” when wanted to “parseInt or parseFloat” from string like “Sometext 330”
JavaScript
x
3
1
Var a = "Sometext 330"
2
return parseFloat(a);
3
and it will return “NaN” but i need integer or float 330
Advertisement
Answer
You could sanitize your string first so only digit’s remain in the string before parsing the number.
edit: now it’s even safer as it will accept Number types without blowing up.
JavaScript
1
27
27
1
var a = "Sometext 330"
2
3
function safeParseFloat(val) {
4
return parseFloat(isNaN(val) ? val.replace(/[^d.]+/g, '') : val)
5
}
6
7
function superSafeParseFloat(val) {
8
if (isNaN(val)) {
9
if ((val = val.match(/([0-9.,]+d)/g))) {
10
val = val[0].replace(/[^d.]+/g, '')
11
}
12
}
13
return parseFloat(val)
14
}
15
16
console.log(
17
safeParseFloat(a),
18
safeParseFloat(2000.69)
19
)
20
21
console.log(
22
superSafeParseFloat('blah $2,000,000.69 AUD'),
23
superSafeParseFloat('blah $8008 USD'),
24
superSafeParseFloat('NotANumber'),
25
superSafeParseFloat(8008.69),
26
superSafeParseFloat('... something 500.5... test')
27
)