showing results for - "number to words jq"
Glynn
12 Jul 2016
1
2//HTML Start
3<input type="number" id="number" placeholder="Number...">
4  <h5 class="result"></h5>
5//HTML End
6
7$("input#number").keyup(function(){
8  var number = $(this).val();
9  var words = numberToWords(number);
10  $(".ntw .result").text(words);
11});
12
13function numberToWords(number) {
14    var digit = ['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine'];
15    var elevenSeries = ['ten', 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen'];
16    var countingByTens = ['twenty', 'thirty', 'forty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety'];
17    var shortScale = ['', 'thousand', 'million', 'billion', 'trillion'];
18    number = number.toString();
19    number = number.replace(/[\, ]/g, '');
20    if (number != parseFloat(number)) return 'not a number';
21    var x = number.indexOf('.');
22    if (x == -1) x = number.length;
23    if (x > 15) return 'too big';
24    var n = number.split('');
25    var str = '';
26    var sk = 0;
27    for (var i = 0; i < x; i++) {
28        if ((x - i) % 3 == 2) {
29            if (n[i] == '1') {
30                str += elevenSeries[Number(n[i + 1])] + ' ';
31                i++;
32                sk = 1;
33            } else if (n[i] != 0) {
34                str += countingByTens[n[i] - 2] + ' ';
35                sk = 1;
36            }
37        } else if (n[i] != 0) {
38            str += digit[n[i]] + ' ';
39            if ((x - i) % 3 == 0) str += 'hundred ';
40            sk = 1;
41        }
42        if ((x - i) % 3 == 1) {
43            if (sk) str += shortScale[(x - i - 1) / 3] + ' ';
44            sk = 0;
45        }
46    }
47    if (x != number.length) {
48        var y = number.length;
49        str += 'point ';
50        for (var i = x + 1; i < y; i++) str += digit[n[i]] + ' ';
51    }
52    str = str.replace(/\number+/g, ' ');
53    str = str.replace(/\s+/g, '-').toLowerCase();
54    return "" + str.trim() + ".";
55}