我遇到空格問題。另外,在諸如54個數字之間需要破折號;然而,我正在破解數字,例如五萬。以字符串形式返回數字輸入Javascript
此外,輸出後我不需要空格,但我一直有問題輸出空格。
任何想法?
PS:我研究了Convert digits into words with JavaScript - 我希望我的版本能夠正常工作。
function number2words(n) {
a = ['', 'one ', 'two ', 'three ', 'four ', 'five ', 'six ', 'seven ', 'eight ', 'nine ', 'ten ', 'eleven ', 'twelve ', 'thirteen ', 'fourteen ', 'fifteen ', 'sixteen ', 'seventeen ', 'eighteen ', 'nineteen '];
b = ['', '', 'twenty', 'thirty', 'forty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety'];
c = ['', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten', 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen'];
if ((n = n.toString()).length > 9) return false;
num = ('000000000' + n).substr(-9).match(/^(\d{2})(\d{2})(\d{2})(\d{1})(\d{2})$/);
if (!num)
return;
var str = '';
dash = '-';
if (c[num[5][1]] == '')
dash = '';
if (n <= 19 && n != 0)
return c[n];
else if (n == 0)
return 'zero';
else if (n == 20 || n == 30 || n == 40 || n == 50 || n == 60 || n == 70 || n == 80 || n == 90)
return b[n[0]];
else
str += (num[1] != 0) ? (a[Number(num[1])] || b[num[1][0]] + '-' + a[num[1][1]]) + 'million ' : '';
str += (num[2] != 0) ? (a[Number(num[2])] || b[num[2][0]] + '-' + a[num[2][1]]) + 'hundred ' : '';
str += (num[3] != 0) ? (a[Number(num[3])] || b[num[3][0]] + '-' + a[num[3][1]]) + 'thousand ' : '';
str += (num[4] != 0) ? (a[Number(num[4])] || b[num[4][0]] + '-' + a[num[4][1]]) + 'hundred' : '';
str += (num[5] != 0) ? ((str != '') ? ' ' : '') + (a[Number(num[5])] || b[num[5][0]] + dash + a[num[5][1]]) : '';
console.log(str[str.length - 1], str.length);
if (str[str.length - 1] == " ") {
var sl = str.slice(0, str.length - 1);
return sl;
}
return str;
}
console.log(number2words(15007));
console.log(number2words(464097));
http://stackoverflow.com/questions/5529934/javascript-numbers-to-words – mplungjan
所以兩個人發現了兩個重複。 – mplungjan
我的問題不是重複的。我的問題是基於原始的答案,但編輯我需要幫助弄清楚如何解決小錯誤。 –