Aim: Write an HTML page including any required Javascript that takes a number from one text field in the range of 0 to 999 and shows it in another text field in words. If the number is out of range, it should show “out of range” and if it is not a number, it should show “not a number” message in the result box.

Program:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>PROGRAM</title> 
    <style>
        body {
            background-color: pink;
            text-align: center;
        }
        .container {
            margin-top: 50px;
        }
        input, button {
            margin: 10px;
        }
    </style>
</head>
<body>

<div class="container">
    <h1>Program : </h1>
    <form name="f1">
        <input name="tb1" min="0" type="text" class="form-control" placeholder="Enter any Number 0 to 999" />
        <button onclick="return validateForm()" type="button" class="btn btn-default">Submit</button>
        <hr/>
        <h1>Output</h1>
        <input type="text" class="form-control" id="output" name="output" readonly />
    </form>
</div>

<script>
function validateForm() {
    var d = document.forms["f1"];

    if (d.tb1.value.trim() === "") {
        alert("Please enter a number between 0 and 999");
        d.tb1.focus();
        return false;
    }
    if (isNaN(d.tb1.value) || d.tb1.value < 0 || d.tb1.value > 999) {
        d.output.value = "Out of Range";
        return false;
    }
    d.output.value = toWords(d.tb1.value);
}

var dg = ['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine'];
var tn = ['ten', 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen'];
var tw = ['twenty', 'thirty', 'forty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety'];

function toWords(s) {
    s = s.toString().replace(/[\, ]/g, '');
    if (isNaN(s)) return 'Not a number';
    
    let num = parseInt(s);
    if (num === 0) return 'zero';
    
    let words = '';
    
    if (num >= 100) {
        words += dg[Math.floor(num / 100)] + ' hundred ';
        num %= 100;
    }
    
    if (num >= 20) {
        words += tw[Math.floor(num / 10) - 2] + ' ';
        num %= 10;
    } else if (num >= 10) {
        words += tn[num - 10] + ' ';
        num = 0;
    }
    
    if (num > 0) {
        words += dg[num] + ' ';
    }

    return words.trim();
}
</script>

</body>
</html>
        
;