I have to cenvert numbers to words. Problem is that arrays return result only in the first nested if I use them in the others return undefined. For example:
100 - one hundred
101 - undefined hundred and one
120 - undefined hundred and twenty
121 - undefined hundred and undefined one.
Can you tell why this happens?
HTML:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script src="Problem 8. Number as words.js"></script>
</head>
<body>
<p>number <input type="text" id="digit"></p>
<input type="button" id="button" value="Check">
<div id="output"></div>
</body>
</html>
JavaSript:
onload = function () {
var digit = document.getElementById('digit');
var button = document.getElementById('button');
var output = document.getElementById('output');
var units = ['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine'];
var tenths = ['twenty', 'thirty', 'fourty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety'];
var toTwenty = ['ten', 'eleven', ' twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen'];
function check() {
var num = digit.value;
if (num>=0 && num<10) {
output.innerHTML = units[num];
}
else if (num>=10 && num<20){
output.innerHTML = toTwenty[num%10];
}
else if (num>=20 && num<100) {
if (num%10==0){
output.innerHTML = tenths[num / 10 - 2];
}
else {
output.innerHTML = tenths[num / 10 - 2] + ' ' + units[num % 10];
}
}
else if(num>=100 && num<1000) {
if (num%100==0) {
output.innerHTML = units[num / 100] + ' hundred';
}
else if (num%100>0 && num%100<10) {
output.innerHTML = units[num / 100] + ' hundred and ' + units[num %10];
}
else if (num%100>=10 && num%100<20) {
output.innerHTML = units[num / 100] + ' hundred and ' + toTwenty[num % 10];
}
else if (num%10==0) {
output.innerHTML = units[num / 100] + ' hundred and ' + tenths[(num % 100) / 10 - 2];
}
else {
output.innerHTML = units[num / 100] + ' hundred and ' + tenths[(num % 100) / 10 - 2] + ' ' + units[num % 10];
}
}
}
button.addEventListener('click', check);
}