I´m doing a function to convert numbers in letters (three hundred twenty-one) into the real number (321)
function parseInt(string) {
var numberContainer = []
const leyend = [
["one",1],["two",2],["three",3],["four",4],["five",5],["six",6],["seven",7],["eight",8],["nine",9],["ten",10],["twenty",20],["thirty",30],["forty",40],["fifty",50],["sixty",60],
["seventy",70],["eighty",80],["ninety",90],
["eleven",11],["twelve",12],["thirteen",13],["fourteen",14],["fifteen",15],["sixteen",16],["seventeen",17],["eighteen",18],["nineteen",19],["hundred",100],
["thousand",1000],["-",false],["and",false]
]
var stringContainer = string.split(" ");
//Conditionals to fix any problems with the use of "and" and "-"
for (let i=0;i<stringContainer.length;i++){
for (let j=0;j<leyend.length;j++){
if (stringContainer[i] === leyend[j][0]){
numberContainer.push(leyend[j][1])
}
else if (stringContainer[i].includes("-")){
var res = stringContainer[i].split("-");
stringContainer[i] = res[0];
stringContainer.push(res[1]);
}
else if (stringContainer[i].includes(" and ")){
var res = stringContainer[i].split("and");
stringContainer[i] = res[0];
stringContainer.push(res[1]);
}
}
}
const definitiveNumber = numberContainer.reduce((a, b) => a < b ? a*b : a+b);
return definitiveNumber
}
I´m having problems. The function works perfectly until it hits numbers like 1000.
Once I pass to the function numbers like 1250, 1388, 2956…etc The function doesn´t convert them right.
I don´t get why it works with units, decimals, and hundreds, but it doesn´t once the word “thousand” come up
–UPDATE: the problem doesn´t seem to be in thousand. But rather in that the numbers that come with “thousand” the “Hundreds” doesn´t add uo. For example 3033 returns correctly. But 3233 doesn´t.
console.log(parseInt("nine hundred and fifty")) // correct, returns 950
console.log(parseInt("sixty-four")) // correct, returns 64
console.log(parseInt("three hundred seventy two")) // correct, returns 372
console.log(parseInt("three thousand thirty three")) // correct, returns 3033
console.log(parseInt("three thousand three hundred and six")) // wrong, returns 3109
console.log(parseInt("eight thousand five hundred fifty-seven")) // wrong, returns 8162
console.log(parseInt("five thousand four hundred fifty-seven")) // wrong, returns 5161
