Reputation: 1
Given a string that represents a number use parseInt to convert string to number. I wrote a working function, but did not account for decimal numbers. Is there a way to convert decimals using parseInt? This is as far as I've gotten trying to account for decimals. The problem with this is NaN being returned. I can't think of a solution to implement that filters NaN from the results. The ultimate goal is to compare the two strings. My solution must use parseInt.
function convertStr(str1, str2) {
let num1 = str1.split('')
let num2 = str2.split('');
num1 = num1.map(str => parseInt(str));
num2 = num2.map(str => parseInt(str));
console.log(num1);
console.log(num2);
}
Any help is greatly appreciated.
Upvotes: 0
Views: 92
Reputation: 23505
I think this is a good step to what you are seeking for :
The question is : What do you want as output when encountering decimal value?
// Soluce to replace NaN by '.'
function convertStrReplace(str1) {
let num1 = str1.split('')
num1 = num1.map(str => parseInt(str)).map(x => isNaN(x) ? '.' : x);
console.log(num1);
}
// Soluce to ignore NaN
function convertStrIgnore(str1) {
let num1 = str1.split('')
num1 = num1.map(str => parseInt(str)).filter(x => !isNaN(x));
console.log(num1);
}
convertStrReplace('17,52');
convertStrIgnore('17,52');
Syntax alternative
function convertStrFilter(str1) {
const num1 = [
...str1,
].map(str => parseInt(str)).filter(x => !isNaN(x));
console.log(num1);
}
convertStrFilter('17,52');
Explaination about integer and string differences
// String and integer differences
// Put a number into a string
const str = '9000';
console.log(typeof str, str);
// Put a number into a number
const number = 9000;
console.log(typeof number, number);
// Compare both (compare value and type)
console.log('equality ===', str === number);
// Compare both (compare value)
console.log('equality ==', str == number);
const numberFromString = parseInt(str);
console.log(typeof numberFromString, numberFromString);
// Compare both (compare value and type)
console.log('equality ===', number === numberFromString);
Upvotes: 2