convert string to number node.js
I'm trying to convert req.params to Number because that is what I defined in my schema for year param.
I have tried
req.params.year = parseInt( req.params.year, 10 );
and
Number( req.params.year);
and
1*req.params.year;
but non of them works. Do I need to install something?
Solution 1:
You do not have to install something.
parseInt(req.params.year, 10);
should work properly.
console.log(typeof parseInt(req.params.year)); // returns 'number'
What is your output, if you use parseInt? is it still a string?
Solution 2:
Using parseInt() is a bad idea mainly because it never fails. Also because some results can be unexpected, like in the case of INFINITY.
Below is the function for handling unexpected behaviour.
function cleanInt(x) {
x = Number(x);
return x >= 0 ? Math.floor(x) : Math.ceil(x);
}
See results of below test cases.
console.log("CleanInt: ", cleanInt('xyz'), " ParseInt: ", parseInt('xyz'));
console.log("CleanInt: ", cleanInt('123abc'), " ParseInt: ", parseInt('123abc'));
console.log("CleanInt: ", cleanInt('234'), " ParseInt: ", parseInt('234'));
console.log("CleanInt: ", cleanInt('-679'), " ParseInt: ", parseInt('-679'));
console.log("CleanInt: ", cleanInt('897.0998'), " ParseInt: ", parseInt('897.0998'));
console.log("CleanInt: ", cleanInt('Infinity'), " ParseInt: ", parseInt('Infinity'));
result:
CleanInt: NaN ParseInt: NaN
CleanInt: NaN ParseInt: 123
CleanInt: 234 ParseInt: 234
CleanInt: -679 ParseInt: -679
CleanInt: 897 ParseInt: 897
CleanInt: Infinity ParseInt: NaN
Solution 3:
Not a full answer Ok so this is just to supplement the information about parseInt, which is still very valid. Express doesn't allow the req or res objects to be modified at all (immutable). So if you want to modify/use this data effectively, you must copy it to another variable (var year = req.params.year).