Convert digits into words with JavaScript

后端 未结 27 1455
我寻月下人不归
我寻月下人不归 2020-11-22 15:08

I am making a code which converts the given amount into words, heres is what I have got after googling. But I think its a little lengthy code to achieve a simple task. Two R

27条回答
  •  悲&欢浪女
    2020-11-22 15:58

    This is also in response to naomik's excellent post! Unfortunately I don't have the rep to post in the correct place but I leave this here in case it can help anyone.

    If you need British English written form you need to make some adaptions to the code. British English differs from the American in a couple of ways. Basically you need to insert the word 'and' in two specific places.

    1. After a hundred assuming there are tens and ones. E.g One hundred and ten. One thousand and seventeen. NOT One thousand one hundred and.
    2. In certain edges, after a thousand, a million, a billion etc. when there are no smaller units. E.g. One thousand and ten. One million and forty four. NOT One million and one thousand.

    The first situation can be addressed by checking for 10s and 1s in the makeGroup method and appending 'and' when they exist.

    makeGroup = ([ones,tens,huns]) => {
    var adjective = this.num(ones) ? ' hundred and ' : this.num(tens) ? ' hundred and ' : ' hundred';
    return [
      this.num(huns) === 0 ? '' : this.a[huns] + adjective,
      this.num(ones) === 0 ? this.b[tens] : this.b[tens] && this.b[tens] + '-' || '',
      this.a[tens+ones] || this.a[ones]
    ].join('');
    

    };

    The second case is more complicated. It is equivalent to

    • add 'and' to 'a million, a thousand', or 'a billion' if the antepenultimate number is zero. e.g.

    1,100,057 one million one hundred thousand and fifty seven. 5,000,006 five million and six

    I think this could be implemented in @naomik's code through the use of a filter function but I wasn't able to work out how. In the end I settled on hackily looping through the returned array of words and using indexOf to look for instances where the word 'hundred' was missing from the final element.

提交回复
热议问题