Convert String To Either Integer Or Float In Javascript
Is there a straightforward way to parse a string to either integer or float if I don't know if the variable is integer-number-like or decimal-number-like? a = '2'; // => parse t
Solution 1:
Multiply string which has number data with 1. You will get the Numeric data value.
var int_value = "string" * 1;
In your case
a = '2' * 1; // => parse to integerb = '2.1' * 1; // => parse to floatc = '2.0' * 1; // => parse to floatd = 'text' * 1; // => don't parse //NaN value
For last one you will get NaN
value. Manually handle for NaN value
Solution 2:
Just wrap it in Number()
Number('123') === 123
Number('-123.456') === -123.456
Solution 3:
That's how I finally solved it. I didn't find any other solution than to add the variable type to the variable ...
var obj = {
a: '2',
b: '2.1',
c: '2.0',
d: 'text'
};
// Explicitly remember the variable typefor (key in obj) {
var value = obj[key], type;
if ( isNaN(value) || value === "" ) {
type = "string";
}
else {
if (value.indexOf(".") === -1) {
type = "integer";
}
else {
type = "float";
}
value = +value; // Convert string to number
}
obj[key] = {
value: value,
type: type
};
}
document.write("<pre>" + JSON.stringify(obj, 0, 4) + "</pre>");
Solution 4:
You can use:
functionparse(x){
return x==x*1?x*1:x
}
functionparse(x){
return x==x*1?x*1:x
}
console.log(parse(1),typeofparse(1))
console.log(parse("1"),typeofparse("1"))
console.log(parse("1.1"),typeofparse("1.1"))
console.log(parse("1A"),typeofparse("1A"))
Post a Comment for "Convert String To Either Integer Or Float In Javascript"