Converting Numbers into Words

情到浓时终转凉″ 提交于 2020-05-14 02:27:51

问题


I have taken this code from Stackoverflow and modified it, but i am unable to convert number for more than 3 digits.

Here is the code:

var num = this.rawValue;
var a = ['','one ','two ','three ','four ', 'five ','six ','seven ','eight ','nine ','ten ','eleven ','twelve ', 'thirteen  ','fourteen ','fifteen ','sixteen ','seventeen ','eighteen ','nineteen '];
var b = ['', '', 'twenty','thirty','forty','fifty', 'sixty','seventy','eighty','ninety'];
var c = ['thousand', 'million', ''];

num = num.toString();

num = ( '000000000' + num ).substr( -9 ); // // Make number into a predictiable nine character string
num = num.match( /.{3}/g ); // Split string into chuncks of three numbers then reverse order of returned array

var words = '';

for( var i = 0; i < c.length; i++ ) {

    var n = num[i];
    var str = '';
    str += ( words != '' ) ? ' ' + c[i] + ' ' : '';
    str += ( n[0] != 0 ) ? ( a[Number( n[0] )] + 'hundred ' ) : '';
    n = n.substr( 1 );
    str += ( n != 0 ) ? ( ( str != '' ) ? 'and ' : '' ) + ( a[Number( n )] || b[n[0]] + ' ' + a[n[1]] ) : '';
    words += str;

}

data.Text.TextField1.rawValue= words;

I want to convert number into words for more than 3 digits and to also consider decimal values.

The current code converts up to thousand and it interprets values before decimal point as undefined. The above code was used in javascript under adobe form (sap).


回答1:


In the for loop replace c[i] by c[c.length-1-i]. This works for me. I just found out that the index specified for the Array c gave wrong results because it kinda went from the wrong direction.

I’m sure this could be optimized in other ways as well.

JSFiddle for testing and experimenting.



来源:https://stackoverflow.com/questions/29405690/converting-numbers-into-words

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!