将数字转换为单词

时间:2015-04-02 05:37:16

标签: javascript numbers number-formatting

我从Stackoverflow获取此代码并对其进行修改,但我无法将数字转换为超过3位数。

以下是代码:

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;

我想将数字转换为超过3位数的单词,并且还要考虑小数值。

当前代码最多转换为千位,并将小数点前的值解释为未定义。以上代码在adobe form(sap)下的javascript中使用。

1 个答案:

答案 0 :(得分:0)

for循环中,将c[i]替换为c[c.length-1-i]。这适合我。我刚刚发现为数组c指定的索引给出了错误的结果,因为它从错误的方向开始。

我确信这也可以通过其他方式进行优化。

JSFiddle for testing and experimenting