使用JavaScript将数字转换为单词

时间:2013-02-08 06:29:46

标签: javascript

我正在编写一个代码,将给定的数量转换为单词,继承人是我在谷歌搜索后得到的。但我觉得它有点冗长的代码来完成一个简单的任务。 两个正则表达式和两个for循环,我想要更简单的东西。

我试图让它尽可能短。并将发布我想出的内容

有什么建议吗?

var th = ['','thousand','million', 'billion','trillion'];
var dg = ['zero','one','two','three','four', 'five','six','seven','eight','nine'];
 var tn = ['ten','eleven','twelve','thirteen', 'fourteen','fifteen','sixteen', 'seventeen','eighteen','nineteen'];
 var tw = ['twenty','thirty','forty','fifty', 'sixty','seventy','eighty','ninety'];

function toWords(s) {
    s = s.toString();
    s = s.replace(/[\, ]/g,'');
    if (s != parseFloat(s)) return 'not a number';
    var x = s.indexOf('.');
    if (x == -1)
        x = s.length;
    if (x > 15)
        return 'too big';
    var n = s.split(''); 
    var str = '';
    var sk = 0;
    for (var i=0;   i < x;  i++) {
        if ((x-i)%3==2) { 
            if (n[i] == '1') {
                str += tn[Number(n[i+1])] + ' ';
                i++;
                sk=1;
            } else if (n[i]!=0) {
                str += tw[n[i]-2] + ' ';
                sk=1;
            }
        } else if (n[i]!=0) { // 0235
            str += dg[n[i]] +' ';
            if ((x-i)%3==0) str += 'hundred ';
            sk=1;
        }
        if ((x-i)%3==1) {
            if (sk)
                str += th[(x-i-1)/3] + ' ';
            sk=0;
        }
    }

    if (x != s.length) {
        var y = s.length;
        str += 'point ';
        for (var i=x+1; i<y; i++)
            str += dg[n[i]] +' ';
    }
    return str.replace(/\s+/g,' ');
}

另外,上面的代码转换为英文编号系统,如百万/亿,我不是南亚编号系统。比如Lakhs和Crores

32 个答案:

答案 0 :(得分:89)

更新:看起来这比我想象的更有用。我刚刚在npm发布了这个。 https://www.npmjs.com/package/num-words


这是一个更短的代码。一个RegEx,没有循环。在南亚编号系统中按你的意愿转换

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'];

function inWords (num) {
    if ((num = num.toString()).length > 9) return 'overflow';
    n = ('000000000' + num).substr(-9).match(/^(\d{2})(\d{2})(\d{2})(\d{1})(\d{2})$/);
    if (!n) return; var str = '';
    str += (n[1] != 0) ? (a[Number(n[1])] || b[n[1][0]] + ' ' + a[n[1][1]]) + 'crore ' : '';
    str += (n[2] != 0) ? (a[Number(n[2])] || b[n[2][0]] + ' ' + a[n[2][1]]) + 'lakh ' : '';
    str += (n[3] != 0) ? (a[Number(n[3])] || b[n[3][0]] + ' ' + a[n[3][1]]) + 'thousand ' : '';
    str += (n[4] != 0) ? (a[Number(n[4])] || b[n[4][0]] + ' ' + a[n[4][1]]) + 'hundred ' : '';
    str += (n[5] != 0) ? ((str != '') ? 'and ' : '') + (a[Number(n[5])] || b[n[5][0]] + ' ' + a[n[5][1]]) + 'only ' : '';
    return str;
}

document.getElementById('number').onkeyup = function () {
    document.getElementById('words').innerHTML = inWords(document.getElementById('number').value);
};
<span id="words"></span>
<input id="number" type="text" />

唯一的限制是,你可以转换最多9个数字,我认为这在大多数情况下已经足够了..

答案 1 :(得分:28)

  

&#34; 看似简单的任务。&#34; - Potatoswatter

事实上。这个问题的细节中有许多小恶魔。解决这个问题非常有趣。

编辑:此更新采用了更多的组合方法。以前有一个很大的功能包含了其他一些专有功能。相反,这次我们定义了可用于多种任务的通用可重用函数。在我们看一下numToWords本身......

之后,有关这些内容的更多信息
// numToWords :: (Number a, String a) => a -> String
let numToWords = n => {
  let a = [
    '', 'one', 'two', 'three', 'four',
    'five', 'six', 'seven', 'eight', 'nine',
    'ten', 'eleven', 'twelve', 'thirteen', 'fourteen',
    'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen'
  ];
  let b = [
    '', '', 'twenty', 'thirty', 'forty',
    'fifty', 'sixty', 'seventy', 'eighty', 'ninety'
  ];
  let g = [
    '', 'thousand', 'million', 'billion', 'trillion', 'quadrillion',
    'quintillion', 'sextillion', 'septillion', 'octillion', 'nonillion'
  ];
  // this part is really nasty still
  // it might edit this again later to show how Monoids could fix this up
  let makeGroup = ([ones,tens,huns]) => {
    return [
      num(huns) === 0 ? '' : a[huns] + ' hundred ',
      num(ones) === 0 ? b[tens] : b[tens] && b[tens] + '-' || '',
      a[tens+ones] || a[ones]
    ].join('');
  };
  // "thousands" constructor; no real good names for this, i guess
  let thousand = (group,i) => group === '' ? group : `${group} ${g[i]}`;
  // execute !
  if (typeof n === 'number') return numToWords(String(n));
  if (n === '0')             return 'zero';
  return comp (chunk(3)) (reverse) (arr(n))
    .map(makeGroup)
    .map(thousand)
    .filter(comp(not)(isEmpty))
    .reverse()
    .join(' ');
};

以下是依赖关系:

您会注意到这些要求旁边没有任何文档,因为他们的意图立即明确。 chunk可能是唯一需要花时间消化的人,但它真的不是太糟糕。此外,功能名称为我们提供了很好的指示,它可能是我们以前遇到的功能。

const arr = x => Array.from(x);
const num = x => Number(x) || 0;
const str = x => String(x);
const isEmpty = xs => xs.length === 0;
const take = n => xs => xs.slice(0,n);
const drop = n => xs => xs.slice(n);
const reverse = xs => xs.slice(0).reverse();
const comp = f => g => x => f (g (x));
const not = x => !x;
const chunk = n => xs =>
  isEmpty(xs) ? [] : [take(n)(xs), ...chunk (n) (drop (n) (xs))];

&#34;所以这些让它更好?&#34;

看看代码是如何清理的

// NEW CODE (truncated)
return comp (chunk(3)) (reverse) (arr(n))
    .map(makeGroup)
    .map(thousand)
    .filter(comp(not)(isEmpty))
    .reverse()
    .join(' ');

// OLD CODE (truncated)
let grp = n => ('000' + n).substr(-3);
let rem = n => n.substr(0, n.length - 3);
let cons = xs => x => g => x ? [x, g && ' ' + g || '', ' ', xs].join('') : xs;
let iter = str => i => x => r => {
  if (x === '000' && r.length === 0) return str;
  return iter(cons(str)(fmt(x))(g[i]))
             (i+1)
             (grp(r))
             (rem(r));
};
return iter('')(0)(grp(String(n)))(rem(String(n)));

最重要的是,我们在新代码中添加的实用程序功能可用于您应用中的其他位置。这意味着,作为以这种方式实现numToWords的副作用,我们可以免费获得其他功能。红利苏打!

一些测试

console.log(numToWords(11009));
//=> eleven thousand nine

console.log(numToWords(10000001));
//=> ten million one 

console.log(numToWords(987));
//=> nine hundred eighty-seven

console.log(numToWords(1015));
//=> one thousand fifteen

console.log(numToWords(55111222333));
//=> fifty-five billion one hundred eleven million two hundred 
//   twenty-two thousand three hundred thirty-three

console.log(numToWords("999999999999999999999991"));
//=> nine hundred ninety-nine sextillion nine hundred ninety-nine
//   quintillion nine hundred ninety-nine quadrillion nine hundred
//   ninety-nine trillion nine hundred ninety-nine billion nine
//   hundred ninety-nine million nine hundred ninety-nine thousand
//   nine hundred ninety-one

console.log(numToWords(6000753512));
//=> six billion seven hundred fifty-three thousand five hundred
//   twelve 

Runnable演示

&#13;
&#13;
const arr = x => Array.from(x);
const num = x => Number(x) || 0;
const str = x => String(x);
const isEmpty = xs => xs.length === 0;
const take = n => xs => xs.slice(0,n);
const drop = n => xs => xs.slice(n);
const reverse = xs => xs.slice(0).reverse();
const comp = f => g => x => f (g (x));
const not = x => !x;
const chunk = n => xs =>
  isEmpty(xs) ? [] : [take(n)(xs), ...chunk (n) (drop (n) (xs))];

// numToWords :: (Number a, String a) => a -> String
let numToWords = n => {
  
  let a = [
    '', 'one', 'two', 'three', 'four',
    'five', 'six', 'seven', 'eight', 'nine',
    'ten', 'eleven', 'twelve', 'thirteen', 'fourteen',
    'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen'
  ];
  
  let b = [
    '', '', 'twenty', 'thirty', 'forty',
    'fifty', 'sixty', 'seventy', 'eighty', 'ninety'
  ];
  
  let g = [
    '', 'thousand', 'million', 'billion', 'trillion', 'quadrillion',
    'quintillion', 'sextillion', 'septillion', 'octillion', 'nonillion'
  ];
  
  // this part is really nasty still
  // it might edit this again later to show how Monoids could fix this up
  let makeGroup = ([ones,tens,huns]) => {
    return [
      num(huns) === 0 ? '' : a[huns] + ' hundred ',
      num(ones) === 0 ? b[tens] : b[tens] && b[tens] + '-' || '',
      a[tens+ones] || a[ones]
    ].join('');
  };
  
  let thousand = (group,i) => group === '' ? group : `${group} ${g[i]}`;
  
  if (typeof n === 'number')
    return numToWords(String(n));
  else if (n === '0')
    return 'zero';
  else
    return comp (chunk(3)) (reverse) (arr(n))
      .map(makeGroup)
      .map(thousand)
      .filter(comp(not)(isEmpty))
      .reverse()
      .join(' ');
};


console.log(numToWords(11009));
//=> eleven thousand nine

console.log(numToWords(10000001));
//=> ten million one 

console.log(numToWords(987));
//=> nine hundred eighty-seven

console.log(numToWords(1015));
//=> one thousand fifteen

console.log(numToWords(55111222333));
//=> fifty-five billion one hundred eleven million two hundred 
//   twenty-two thousand three hundred thirty-three

console.log(numToWords("999999999999999999999991"));
//=> nine hundred ninety-nine sextillion nine hundred ninety-nine
//   quintillion nine hundred ninety-nine quadrillion nine hundred
//   ninety-nine trillion nine hundred ninety-nine billion nine
//   hundred ninety-nine million nine hundred ninety-nine thousand
//   nine hundred ninety-one

console.log(numToWords(6000753512));
//=> six billion seven hundred fifty-three thousand five hundred
//   twelve
&#13;
&#13;
&#13;

如果您想查看ES5变体

,可以使用babel.js来转换代码

答案 2 :(得分:12)

我花了一些时间为此开发更好的解决方案。它可以处理非常大的数字但是一旦它们超过16位,你就可以将数字作为字符串传递。关于JavaScript数量限制的事情。

&#13;
&#13;
Document doc = new Document(srcDoc);
doc.print("Microsoft XPS Document Writer");
&#13;
&#13;
&#13;

答案 3 :(得分:8)

您可能想尝试递归。它适用于0到999999之间的数字。请记住,(~~)与Math.floor相同

&#13;
&#13;
var num = "zero one two three four five six seven eight nine ten eleven twelve thirteen fourteen fifteen sixteen seventeen eighteen nineteen".split(" ");
var tens = "twenty thirty forty fifty sixty seventy eighty ninety".split(" ");

function number2words(n){
    if (n < 20) return num[n];
    var digit = n%10;
    if (n < 100) return tens[~~(n/10)-2] + (digit? "-" + num[digit]: "");
    if (n < 1000) return num[~~(n/100)] +" hundred" + (n%100 == 0? "": " " + number2words(n%100));
    return number2words(~~(n/1000)) + " thousand" + (n%1000 != 0? " " + number2words(n%1000): "");
}
&#13;
&#13;
&#13;

答案 4 :(得分:4)

2021 年 2 月更新

虽然这个问题在 8 年前就提出了各种解决方案和答案,但最简单的解决方案,只需在数组中插入一个名称即可轻松更新以增加规模,无需修改代码;并且使用非常短的代码是下面的功能。

此解决方案适用于数字的英文阅读(不是南亚系统),并使用标准的美国英语(美国方式)书写大数。即它不使用英国系统(英国系统使用“和”一词,例如:“三十二万二千”)。

提供测试用例和输入字段。

请记住,我们要转换为单词的是“无符号整数”。

您可以将 scale[] array 增加到超过六千位。

由于函数很短,您可以将其用作内部函数,例如在使用十进制数的货币转换中,并为整数部分和小数部分调用两次。

希望有用。

/********************************************************
* @function    : integerToWords()
* @purpose     : Converts Unsigned Integers to Words
*                Using String Triplet Array.
* @version     : 1.05
* @author      : Mohsen Alyafei
* @date        : 15 January 2021
* @param       : {number} [integer numeric or string]
* @returns     : {string} The wordified number string
********************************************************/
const Ones  = ["","One","Two","Three","Four","Five","Six","Seven","Eight","Nine","Ten",
                "Eleven","Twelve","Thirteen","Fourteen","Fifteen","Sixteen","Seventeen","Eighteen","Nineteen"],
      Tens  = ["","","Twenty","Thirty","Forty","Fifty","Sixty","Seventy","Eighty","Ninety","Hundred"],
      Scale = ["","Thousand","Million","Billion","Trillion","Quadrillion","Quintillion","Sextillion"];
//==================================
const integerToWords = (n = 0) => {
if (n == 0) return "Zero";                                   // check for zero
n = ("0".repeat(2*(n+="").length % 3) + n).match(/.{3}/g);   // create triplets array
if (n.length > Scale.length) return "Too Large";             // check if larger than scale array
let out= ""; return n.forEach((Triplet,pos) => {             // loop into array for each triplet
if (+Triplet) { out+=' ' +(+Triplet[0] ? Ones[+Triplet[0]]+' '+ Tens[10] : "") +
      ' ' + (+Triplet.substr(1)< 20 ? Ones[+Triplet.substr(1)] :
             Tens[+Triplet[1]] + (+Triplet[2] ? "-" : "") + Ones[+Triplet[2]]) +
      ' ' +  Scale[n.length-pos-1]; }
}),out.replace(/\s+/g,' ').trim();};                         // lazy job using trim()
//==================================








//=========================================
//             Test Cases
//=========================================
var r=0; // test tracker
r |= test(0,"Zero");
r |= test(5,"Five");
r |= test(10,"Ten");
r |= test(19,"Nineteen");
r |= test(33,"Thirty-Three");
r |= test(100,"One Hundred");
r |= test(111,"One Hundred Eleven");
r |= test(890,"Eight Hundred Ninety");
r |= test(1234,"One Thousand Two Hundred Thirty-Four");
r |= test(12345,"Twelve Thousand Three Hundred Forty-Five");
r |= test(123456,"One Hundred Twenty-Three Thousand Four Hundred Fifty-Six");
r |= test(1234567,"One Million Two Hundred Thirty-Four Thousand Five Hundred Sixty-Seven");
r |= test(12345678,"Twelve Million Three Hundred Forty-Five Thousand Six Hundred Seventy-Eight");
r |= test(123456789,"One Hundred Twenty-Three Million Four Hundred Fifty-Six Thousand Seven Hundred Eighty-Nine");
r |= test(1234567890,"One Billion Two Hundred Thirty-Four Million Five Hundred Sixty-Seven Thousand Eight Hundred Ninety");
r |= test(1001,"One Thousand One");
r |= test(10001,"Ten Thousand One");
r |= test(100001,"One Hundred Thousand One");
r |= test(1000001,"One Million One");
r |= test(10000001,"Ten Million One");
r |= test(100000001,"One Hundred Million One");
r |= test(12012,"Twelve Thousand Twelve");
r |= test(120012,"One Hundred Twenty Thousand Twelve");
r |= test(1200012,"One Million Two Hundred Thousand Twelve");
r |= test(12000012,"Twelve Million Twelve");
r |= test(120000012,"One Hundred Twenty Million Twelve");
r |= test(75075,"Seventy-Five Thousand Seventy-Five");
r |= test(750075,"Seven Hundred Fifty Thousand Seventy-Five");
r |= test(7500075,"Seven Million Five Hundred Thousand Seventy-Five");
r |= test(75000075,"Seventy-Five Million Seventy-Five");
r |= test(750000075,"Seven Hundred Fifty Million Seventy-Five");
r |= test(1000,"One Thousand");
r |= test(1000000,"One Million");
r |= test(1000000000,"One Billion");
r |= test(1000000000000,"One Trillion");
r |= test("1000000000000000","One Quadrillion");
r |= test("1000000000000000000","One Quintillion");
r |= test("1000000100100100100","One Quintillion One Hundred Billion One Hundred Million One Hundred Thousand One Hundred");

if (r==0) console.log("All Tests Passed.");

//=====================================
// Tester Function
//=====================================
function test(n,should) {
let result = integerToWords(n);
if (result !== should) {console.log(`${n} Output   : ${result}\n${n} Should be: ${should}`);return 1;}
}
<input type="text" name="number" placeholder="Please enter an Integer Number" onkeyup="word.innerHTML=integerToWords(this.value)" />
<div id="word"></div>

答案 5 :(得分:4)

enter image description here

&#13;
&#13;
 <html>

<head>

    <title>HTML - Convert numbers to words using JavaScript</title>

    <script  type="text/javascript">
    	function onlyNumbers(evt) {
    var e = event || evt; // For trans-browser compatibility
    var charCode = e.which || e.keyCode;

    if (charCode > 31 && (charCode < 48 || charCode > 57))
        return false;
    return true;
}

function NumToWord(inputNumber, outputControl) {
    var str = new String(inputNumber)
    var splt = str.split("");
    var rev = splt.reverse();
    var once = ['Zero', ' One', ' Two', ' Three', ' Four', ' Five', ' Six', ' Seven', ' Eight', ' Nine'];
    var twos = ['Ten', ' Eleven', ' Twelve', ' Thirteen', ' Fourteen', ' Fifteen', ' Sixteen', ' Seventeen', ' Eighteen', ' Nineteen'];
    var tens = ['', 'Ten', ' Twenty', ' Thirty', ' Forty', ' Fifty', ' Sixty', ' Seventy', ' Eighty', ' Ninety'];

    numLength = rev.length;
    var word = new Array();
    var j = 0;

    for (i = 0; i < numLength; i++) {
        switch (i) {

            case 0:
                if ((rev[i] == 0) || (rev[i + 1] == 1)) {
                    word[j] = '';
                }
                else {
                    word[j] = '' + once[rev[i]];
                }
                word[j] = word[j];
                break;

            case 1:
                aboveTens();
                break;

            case 2:
                if (rev[i] == 0) {
                    word[j] = '';
                }
                else if ((rev[i - 1] == 0) || (rev[i - 2] == 0)) {
                    word[j] = once[rev[i]] + " Hundred ";
                }
                else {
                    word[j] = once[rev[i]] + " Hundred and";
                }
                break;

            case 3:
                if (rev[i] == 0 || rev[i + 1] == 1) {
                    word[j] = '';
                }
                else {
                    word[j] = once[rev[i]];
                }
                if ((rev[i + 1] != 0) || (rev[i] > 0)) {
                    word[j] = word[j] + " Thousand";
                }
                break;

                
            case 4:
                aboveTens();
                break;

            case 5:
                if ((rev[i] == 0) || (rev[i + 1] == 1)) {
                    word[j] = '';
                }
                else {
                    word[j] = once[rev[i]];
                }
                if (rev[i + 1] !== '0' || rev[i] > '0') {
                    word[j] = word[j] + " Lakh";
                }
                 
                break;

            case 6:
                aboveTens();
                break;

            case 7:
                if ((rev[i] == 0) || (rev[i + 1] == 1)) {
                    word[j] = '';
                }
                else {
                    word[j] = once[rev[i]];
                }
                if (rev[i + 1] !== '0' || rev[i] > '0') {
                    word[j] = word[j] + " Crore";
                }                
                break;

            case 8:
                aboveTens();
                break;

            //            This is optional. 

            //            case 9:
            //                if ((rev[i] == 0) || (rev[i + 1] == 1)) {
            //                    word[j] = '';
            //                }
            //                else {
            //                    word[j] = once[rev[i]];
            //                }
            //                if (rev[i + 1] !== '0' || rev[i] > '0') {
            //                    word[j] = word[j] + " Arab";
            //                }
            //                break;

            //            case 10:
            //                aboveTens();
            //                break;

            default: break;
        }
        j++;
    }

    function aboveTens() {
        if (rev[i] == 0) { word[j] = ''; }
        else if (rev[i] == 1) { word[j] = twos[rev[i - 1]]; }
        else { word[j] = tens[rev[i]]; }
    }

    word.reverse();
    var finalOutput = '';
    for (i = 0; i < numLength; i++) {
        finalOutput = finalOutput + word[i];
    }
    document.getElementById(outputControl).innerHTML = finalOutput;
}
    </script>

</head>

<body>

    <h1>

        HTML - Convert numbers to words using JavaScript</h1>

    <input id="Text1" type="text" onkeypress="return onlyNumbers(this.value);" onkeyup="NumToWord(this.value,'divDisplayWords');"

        maxlength="9" style="background-color: #efefef; border: 2px solid #CCCCC; font-size: large" />

    <br />

    <br />

    <div id="divDisplayWords" style="font-size: 13; color: Teal; font-family: Arial;">

    </div>

</body>

</html>
&#13;
&#13;
&#13;

答案 6 :(得分:3)

将输入字符串转换为数字而不是将其保留为字符串,将解决方案限制为该计算机/浏览器上允许的最大浮点数/整数值。我的脚本下面处理的货币高达1万亿美元 - 1美分:-)。通过添加3或4行代码,我可以扩展到最多可处理999万亿。

var ones = ["","One","Two","Three","Four","Five","Six","Seven","Eight",
            "Nine","Ten","Eleven","Twelve","Thirteen","Fourteen",
            "Fifteen","Sixteen","Seventeen","Eighteen","Nineteen"]; 

var tens = ["","","Twenty","Thirty","Forty","Fifty","Sixty","Seventy",
            "Eighty","Ninety"]; 


function words999(n999)   {    // n999 is an integer less than or equal to 999.
//
// Accept any 3 digit int incl 000 & 999 and return words.
// 

    var words = ''; var Hn = 0; var n99 = 0;

    Hn = Math.floor(n999 / 100);                  // # of hundreds in it

    if (Hn > 0)   {                               // if at least one 100

      words = words99(Hn) + " Hundred";           // one call for hundreds
    }

    n99 = n999 - (Hn * 100);                      // subtract the hundreds.

    words += ((words == '')?'':' ') + words99(n99); // combine the hundreds with tens & ones.

    return words;
}                            // function words999( n999 )

function words99(n99)   {    // n99 is an integer less than or equal to 99.
//
// Accept any 2 digit int incl 00 & 99 and return words.
// 

    var words = ''; var Dn = 0; var Un = 0;

    Dn = Math.floor(n99 / 10);           // # of tens

    Un = n99 % 10;                       // units

    if (Dn > 0 || Un > 0) {

      if (Dn < 2) {

        words += ones[Dn * 10 + Un];     // words for a # < 20

      } else {

        words += tens[Dn];

        if (Un > 0) words += "-" + ones[Un];
      }
    }                               // if ( Dn > 0 || Un > 0 )

    return words;
}                                   // function words99( n99 )

function getAmtInWords(id1, id2) {  // use numeric value of id1 to populate text in id2 
//
// Read numeric amount field and convert into word amount
// 

    var t1 = document.getElementById(id1).value;

    var t2 = t1.trim();

    amtStr = t2.replace(/,/g,'');        // $123,456,789.12 = 123456789.12

    dotPos = amtStr.indexOf('.');        // position of dot before cents, -ve if it doesn't exist.

    if (dotPos > 0) {

      dollars = amtStr.slice(0,dotPos);  // 1234.56 = 1234
      cents   = amtStr.slice(dotPos+1);  // 1234.56 = .56

    } else if (dotPos == 0) {

      dollars = '0';
      cents   = amtStr.slice(dotPos+1);  // 1234.56 = .56

    } else {

      dollars = amtStr.slice(0);         // 1234 = 1234
      cents   = '0'; 
    }

    t1      = '000000000000' + dollars;  // to extend to trillion, use 15 zeros
    dollars =  t1.slice(-12);            // and -15 here.

    billions  = Number(dollars.substr(0,3));
    millions  = Number(dollars.substr(3,3));
    thousands = Number(dollars.substr(6,3));
    hundreds  = Number(dollars.substr(9,3));

    t1 = words999(billions);    bW = t1.trim();   // Billions  in words

    t1 = words999(millions);    mW = t1.trim();   // Millions  in words

    t1 = words999(thousands);   tW = t1.trim();   // Thousands in words

    t1 = words999(hundreds);    hW = t1.trim();   // Hundreds  in words

    t1 = words99(cents);        cW = t1.trim();   // Cents     in words

    var totAmt = '';

    if (bW != '')   totAmt += ((totAmt != '') ? ' '  : '') + bW + ' Billion';
    if (mW != '')   totAmt += ((totAmt != '') ? ' '  : '') + mW + ' Million';
    if (tW != '')   totAmt += ((totAmt != '') ? ' '  : '') + tW + ' Thousand';
    if (hW != '')   totAmt += ((totAmt != '') ? ' '  : '') + hW + ' Dollars';

    if (cW != '')   totAmt += ((totAmt != '') ? ' and ' : '') + cW + ' Cents';

//  alert('totAmt = ' + totAmt);    // display words in a alert

    t1 = document.getElementById(id2).value;

    t2 = t1.trim();

    if (t2 == '')  document.getElementById(id2).value = totAmt;

    return false;
}                        // function getAmtInWords( id1, id2 )

// ======================== [ End Code ] ====================================

答案 7 :(得分:3)

我喜欢我在这里得到的结果,我觉得这个结果很容易阅读,而且很短,足以作为解决方案。

function NumInWords (number) {
  const first = ['','one ','two ','three ','four ', 'five ','six ','seven ','eight ','nine ','ten ','eleven ','twelve ','thirteen ','fourteen ','fifteen ','sixteen ','seventeen ','eighteen ','nineteen '];
  const tens = ['', '', 'twenty','thirty','forty','fifty', 'sixty','seventy','eighty','ninety'];
  const mad = ['', 'thousand', 'million', 'billion', 'trillion'];
  let word = '';

  for (let i = 0; i < mad.length; i++) {
    let tempNumber = number%(100*Math.pow(1000,i));
    if (Math.floor(tempNumber/Math.pow(1000,i)) !== 0) {
      if (Math.floor(tempNumber/Math.pow(1000,i)) < 20) {
        word = first[Math.floor(tempNumber/Math.pow(1000,i))] + mad[i] + ' ' + word;
      } else {
        word = tens[Math.floor(tempNumber/(10*Math.pow(1000,i)))] + '-' + first[Math.floor(tempNumber/Math.pow(1000,i))%10] + mad[i] + ' ' + word;
      }
    }

    tempNumber = number%(Math.pow(1000,i+1));
    if (Math.floor(tempNumber/(100*Math.pow(1000,i))) !== 0) word = first[Math.floor(tempNumber/(100*Math.pow(1000,i)))] + 'hunderd ' + word;
  }
    return word;
}

console.log(NumInWords(89754697976431))

结果是:

  八十九亿七千五百四十五亿六亿九千七百七十七万六千四百三十一

答案 8 :(得分:2)

这是对@ LordZardeck对@naomik's excellent answer above的评论的回应。对不起,我会直接发表评论,但我之前从未发过帖,所以我没有特权这样做,所以我在这里发帖。

无论如何,我刚刚在上周末将ES5版本转换为更易读的形式,所以我在这里分享它。这应该忠实于原作(包括最近的编辑),我希望命名清晰准确。

function int_to_words(int) {
  if (int === 0) return 'zero';

  var ONES  = ['','one','two','three','four','five','six','seven','eight','nine','ten','eleven','twelve','thirteen','fourteen','fifteen','sixteen','seventeen','eighteen','nineteen'];
  var TENS  = ['','','twenty','thirty','fourty','fifty','sixty','seventy','eighty','ninety'];
  var SCALE = ['','thousand','million','billion','trillion','quadrillion','quintillion','sextillion','septillion','octillion','nonillion'];

  // Return string of first three digits, padded with zeros if needed
  function get_first(str) {
    return ('000' + str).substr(-3);
  }

  // Return string of digits with first three digits chopped off
  function get_rest(str) {
    return str.substr(0, str.length - 3);
  }

  // Return string of triplet convereted to words
  function triplet_to_words(_3rd, _2nd, _1st) {
    return (_3rd == '0' ? '' : ONES[_3rd] + ' hundred ') + (_1st == '0' ? TENS[_2nd] : TENS[_2nd] && TENS[_2nd] + '-' || '') + (ONES[_2nd + _1st] || ONES[_1st]);
  }

  // Add to words, triplet words with scale word
  function add_to_words(words, triplet_words, scale_word) {
    return triplet_words ? triplet_words + (scale_word && ' ' + scale_word || '') + ' ' + words : words;
  }

  function iter(words, i, first, rest) {
    if (first == '000' && rest.length === 0) return words;
    return iter(add_to_words(words, triplet_to_words(first[0], first[1], first[2]), SCALE[i]), ++i, get_first(rest), get_rest(rest));
  }

  return iter('', 0, get_first(String(int)), get_rest(String(int)));
}

答案 9 :(得分:2)

如果你需要Cent,那么你可以使用这个

        <script>
            var iWords = ['zero', ' one', ' two', ' three', ' four', ' five', ' six', ' seven', ' eight', ' nine'];
            var ePlace = ['ten', ' eleven', ' twelve', ' thirteen', ' fourteen', ' fifteen', ' sixteen', ' seventeen', ' eighteen', ' nineteen'];
            var tensPlace = ['', ' ten', ' twenty', ' thirty', ' forty', ' fifty', ' sixty', ' seventy', ' eighty', ' ninety'];
            var inWords = [];

            var numReversed, inWords, actnumber, i, j;

            function tensComplication() {
            if (actnumber[i] == 0) {
                inWords[j] = '';
            } else if (actnumber[i] == 1) {
                inWords[j] = ePlace[actnumber[i - 1]];
            } else {
                inWords[j] = tensPlace[actnumber[i]];
            }
            }

            function convertAmount() {
                var numericValue = document.getElementById('bdt').value;
                numericValue = parseFloat(numericValue).toFixed(2);

                var amount = numericValue.toString().split('.');
                var taka = amount[0];
                var paisa = amount[1];
                document.getElementById('container').innerHTML = convert(taka) +" taka and "+ convert(paisa)+" paisa only";
            }
            function convert(numericValue) {
            inWords = []
            if(numericValue == "00" || numericValue =="0"){
                return 'zero';
            }
            var obStr = numericValue.toString();
            numReversed = obStr.split('');
            actnumber = numReversed.reverse();


            if (Number(numericValue) == 0) {
                document.getElementById('container').innerHTML = 'BDT Zero';
                return false;
            }

            var iWordsLength = numReversed.length;
            var finalWord = '';
            j = 0;
            for (i = 0; i < iWordsLength; i++) {
                switch (i) {
                    case 0:
                        if (actnumber[i] == '0' || actnumber[i + 1] == '1') {
                            inWords[j] = '';
                        } else {
                            inWords[j] = iWords[actnumber[i]];
                        }
                        inWords[j] = inWords[j] + '';
                        break;
                    case 1:
                        tensComplication();
                        break;
                    case 2:
                        if (actnumber[i] == '0') {
                            inWords[j] = '';
                        } else if (actnumber[i - 1] !== '0' && actnumber[i - 2] !== '0') {
                            inWords[j] = iWords[actnumber[i]] + ' hundred';
                        } else {
                            inWords[j] = iWords[actnumber[i]] + ' hundred';
                        }
                        break;
                    case 3:
                        if (actnumber[i] == '0' || actnumber[i + 1] == '1') {
                            inWords[j] = '';
                        } else {
                            inWords[j] = iWords[actnumber[i]];
                        }
                        if (actnumber[i + 1] !== '0' || actnumber[i] > '0') {
                            inWords[j] = inWords[j] + ' thousand';
                        }
                        break;
                    case 4:
                        tensComplication();
                        break;
                    case 5:
                        if (actnumber[i] == '0' || actnumber[i + 1] == '1') {
                            inWords[j] = '';
                        } else {
                            inWords[j] = iWords[actnumber[i]];
                        }
                        if (actnumber[i + 1] !== '0' || actnumber[i] > '0') {
                            inWords[j] = inWords[j] + ' lakh';
                        }
                        break;
                    case 6:
                        tensComplication();
                        break;
                    case 7:
                        if (actnumber[i] == '0' || actnumber[i + 1] == '1') {
                            inWords[j] = '';
                        } else {
                            inWords[j] = iWords[actnumber[i]];
                        }
                        inWords[j] = inWords[j] + ' crore';
                        break;
                    case 8:
                        tensComplication();
                        break;
                    default:
                        break;
                }
                j++;
            }


            inWords.reverse();
            for (i = 0; i < inWords.length; i++) {
                finalWord += inWords[i];
            }
            return finalWord;
            }

        </script>

        <input type="text" name="bdt" id="bdt" />
        <input type="button" name="sr1" value="Click Here" onClick="convertAmount()"/>

        <div id="container"></div>

js fiddle

这里的塔卡意味着美元和帕萨意味着分数

答案 10 :(得分:1)

另一种使用余数并支持不同语言的转换:

function numberToWords(number) {
  var result = [];

  var fraction = number.toFixed(2).split('.');
  var integer_part = parseInt(fraction[0]);
  // var fractional_part = parseInt(fraction[1]); -- not handled here

  var previousNumber = null;
  for (var i = 0; i < fraction[0].length; i++) {
    var reminder = Math.floor(integer_part % 10);
    integer_part /= 10;
    var name = getNumberName(reminder, i, fraction[0].length, previousNumber);
    previousNumber = reminder;
    if (name)
      result.push(name);
  }

  result.reverse();
  return result.join(' ');
}

getNumberName函数依赖于语言并处理 9999 之前的数字(但很容易将其扩展为处理更大的数字):

function getNumberName(number, power, places, previousNumber) {
  var result = "";
  if (power == 1) {
    result = handleTeensAndTys(number, previousNumber);
  } else if (power == 0 && places != 1 || number == 0) {
    // skip number that was handled in teens and zero
  } else {
    result = locale.numberNames[number.toString()] + locale.powerNames[power.toString()];
  }

  return result;
}

handleTeensAndTys处理十的倍数:

function handleTeensAndTys(number, previousNumber) {
  var result = "";
  if (number == 1) { // teens
    if (previousNumber in locale.specialTeenNames) {
      result = locale.specialTeenNames[previousNumber];    
    } else if (previousNumber in locale.specialTyNames) {
      result = locale.specialTyNames[previousNumber] + locale.teenSuffix;
    } else {
      result = locale.numberNames[previousNumber] + locale.teenSuffix;    
    }
  } else if (number == 0) { // previousNumber was not handled in teens
    result = locale.numberNames[previousNumber.toString()];
  } else { // other tys
    if (number in locale.specialTyNames) {
      result = locale.specialTyNames[number];
    } else {
      result = locale.numberNames[number];
    }
    result += locale.powerNames[1];
    if (previousNumber != 0) {
      result += " " + locale.numberNames[previousNumber.toString()];
    }
  }
  return result;
}

最后,语言环境示例:

var locale = { // English
  numberNames: {1: "one", 2: "two", 3: "three", 4: "four", 5: "five", 6: "six", 7: "seven", 8: "eight", 9: "nine" },
  powerNames: {0: "", 1: "ty", 2: " hundred", 3: " thousand" },
  specialTeenNames: {0: "ten", 1: "eleven", 2: "twelve" },
  specialTyNames: {2: "twen", 3: "thir", 5: "fif" },
  teenSuffix: "teen"
};

var locale = { // Estonian
  numberNames: {1: "üks", 2: "kaks", 3: "kolm", 4: "neli", 5: "viis", 6: "kuus", 7: "seitse", 8: "kaheksa", 9: "üheksa"},
  powerNames: {0: "", 1: "kümmend", 2: "sada", 3: " tuhat" },
  specialTeenNames: {0: "kümme"},
  specialTyNames: {},
  teenSuffix: "teist"
};

这是一个带有测试的JSFiddle:https://jsfiddle.net/rcrxna7v/15/

答案 11 :(得分:1)

我修改了MC萨满的代码,以解决单个数字具有并在其之前出现的错误

function numberToEnglish( n ) {
		
	var string = n.toString(), units, tens, scales, start, end, chunks, chunksLen, chunk, ints, i, word, words, and = 'and';

	/* Remove spaces and commas */
	string = string.replace(/[, ]/g,"");

	/* Is number zero? */
	if( parseInt( string ) === 0 ) {
		return 'zero';
	}
	
	/* Array of units as words */
	units = [ '', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten', 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen' ];
	
	/* Array of tens as words */
	tens = [ '', '', 'twenty', 'thirty', 'forty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety' ];
	
	/* Array of scales as words */
	scales = [ '', 'thousand', 'million', 'billion', 'trillion', 'quadrillion', 'quintillion', 'sextillion', 'septillion', 'octillion', 'nonillion', 'decillion', 'undecillion', 'duodecillion', 'tredecillion', 'quatttuor-decillion', 'quindecillion', 'sexdecillion', 'septen-decillion', 'octodecillion', 'novemdecillion', 'vigintillion', 'centillion' ];
	
	/* Split user arguemnt into 3 digit chunks from right to left */
	start = string.length;
	chunks = [];
	while( start > 0 ) {
		end = start;
		chunks.push( string.slice( ( start = Math.max( 0, start - 3 ) ), end ) );
	}
	
	/* Check if function has enough scale words to be able to stringify the user argument */
	chunksLen = chunks.length;
	if( chunksLen > scales.length ) {
		return '';
	}
	
	/* Stringify each integer in each chunk */
	words = [];
	for( i = 0; i < chunksLen; i++ ) {
		
		chunk = parseInt( chunks[i] );
		
		if( chunk ) {
			
			/* Split chunk into array of individual integers */
			ints = chunks[i].split( '' ).reverse().map( parseFloat );
		
			/* If tens integer is 1, i.e. 10, then add 10 to units integer */
			if( ints[1] === 1 ) {
				ints[0] += 10;
			}
			
			/* Add scale word if chunk is not zero and array item exists */
			if( ( word = scales[i] ) ) {
				words.push( word );
			}
			
			/* Add unit word if array item exists */
			if( ( word = units[ ints[0] ] ) ) {
				words.push( word );
			}
			
			/* Add tens word if array item exists */
			if( ( word = tens[ ints[1] ] ) ) {
				words.push( word );
			}
			
			/* Add 'and' string after units or tens integer if: */
			if( ints[0] || ints[1] ) {
				
				/* Chunk has a hundreds integer or chunk is the first of multiple chunks */
				if( ints[2] || (i + 1) > chunksLen ) {
					words.push( and );
				}

			
			}
			
			/* Add hundreds word if array item exists */
			if( ( word = units[ ints[2] ] ) ) {
				words.push( word + ' hundred' );
			}
			
		}
		
	}
	
	return words.reverse().join( ' ' );
	
}


// - - - - - Tests - - - - - -

function figure(val) {
  finalFig = numberToEnglish(val);
  document.getElementById("words").innerHTML = finalFig;
}
<span id="words"></span>
<input id="number" type="text" onkeyup=figure(this.value)  />

答案 12 :(得分:1)

很多好的答案。我需要我的印度(南亚)编号系统。我修改了上面的一个代码 - 将它附在此处,以防其他人需要这个。在印度编号系统中,成千上万的群体是2位数,而不是西方系统中的3位。

var IS_SOUTH_ASIAN = true;
function int_to_words(int) {
  if (int === 0) return 'zero';

  var ONES_WORD  = ['','one','two','three','four','five','six','seven','eight','nine','ten','eleven','twelve','thirteen','fourteen','fifteen','sixteen','seventeen','eighteen','nineteen'];
  var TENS_WORD  = ['','','twenty','thirty','fourty','fifty','sixty','seventy','eighty','ninety'];
  var SCALE_WORD_WESTERN = ['','thousand','million','billion','trillion','quadrillion','quintillion','sextillion','septillion','octillion','nonillion'];
  var SCALE_WORD_SOUTH_ASIAN = ['','thousand','lakh','crore','arab','kharab','neel','padma','shankh','***','***'];

  var GROUP_SIZE = (typeof IS_SOUTH_ASIAN != "undefined" && IS_SOUTH_ASIAN) ? 2 : 3;
  var SCALE_WORD = (typeof IS_SOUTH_ASIAN != "undefined" && IS_SOUTH_ASIAN) ? SCALE_WORD_SOUTH_ASIAN : SCALE_WORD_WESTERN;


  // Return string of first three digits, padded with zeros if needed
  function get_first_3(str) {
    return ('000' + str).substr(-(3));
  }
  function get_first(str) { //-- Return string of first GROUP_SIZE digits, padded with zeros if needed, if group size is 2, make it size 3 by prefixing with a '0'
    return (GROUP_SIZE == 2 ? '0' : '') + ('000' + str).substr(-(GROUP_SIZE));
  }


  // Return string of digits with first three digits chopped off
  function get_rest_3(str) {
    return str.substr(0, str.length - 3);
  }
  function get_rest(str) { // Return string of digits with first GROUP_SIZE digits chopped off
    return str.substr(0, str.length - GROUP_SIZE);
  }

  // Return string of triplet convereted to words
  function triplet_to_words(_3rd, _2nd, _1st) {
    return  (_3rd == '0' ? '' : ONES_WORD[_3rd] + ' hundred ') + 
            (_1st == '0' ? TENS_WORD[_2nd] : TENS_WORD[_2nd] && TENS_WORD[_2nd] + '-' || '') + 
            (ONES_WORD[_2nd + _1st] || ONES_WORD[_1st]);  //-- 1st one returns one-nineteen - second one returns one-nine
  }

  // Add to result, triplet words with scale word
  function add_to_result(result, triplet_words, scale_word) {
    return triplet_words ? triplet_words + (scale_word && ' ' + scale_word || '') + ' ' + result : result;
  }

  function recurse (result, scaleIdx, first, rest) {
    if (first == '000' && rest.length === 0) return result;
    var newResult = add_to_result (result, triplet_to_words (first[0], first[1], first[2]), SCALE_WORD[scaleIdx]);
    return recurse (newResult, ++scaleIdx, get_first(rest), get_rest(rest));
  }

  return recurse ('', 0, get_first_3(String(int)), get_rest_3(String(int)));
}

答案 13 :(得分:1)

var inWords = function(totalRent){
//console.log(totalRent);
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 number = parseFloat(totalRent).toFixed(2).split(".");
var num = parseInt(number[0]);
var digit = parseInt(number[1]);
//console.log(num);
if ((num.toString()).length > 9)  return 'overflow';
var n = ('000000000' + num).substr(-9).match(/^(\d{2})(\d{2})(\d{2})(\d{1})(\d{2})$/);
var d = ('00' + digit).substr(-2).match(/^(\d{2})$/);;
if (!n) return; var str = '';
str += (n[1] != 0) ? (a[Number(n[1])] || b[n[1][0]] + ' ' + a[n[1][1]]) + 'crore ' : '';
str += (n[2] != 0) ? (a[Number(n[2])] || b[n[2][0]] + ' ' + a[n[2][1]]) + 'lakh ' : '';
str += (n[3] != 0) ? (a[Number(n[3])] || b[n[3][0]] + ' ' + a[n[3][1]]) + 'thousand ' : '';
str += (n[4] != 0) ? (a[Number(n[4])] || b[n[4][0]] + ' ' + a[n[4][1]]) + 'hundred ' : '';
str += (n[5] != 0) ? (a[Number(n[5])] || b[n[5][0]] + ' ' + a[n[5][1]]) + 'Rupee ' : '';
str += (d[1] != 0) ? ((str != '' ) ? "and " : '') + (a[Number(d[1])] || b[d[1][0]] + ' ' + a[d[1][1]]) + 'Paise ' : 'Only!';
console.log(str);
return str;
}

这是印度卢比的修改代码支持,小数点后2位。

答案 14 :(得分:0)

使用JavaScript和html将数字转换为法语单词-原始法语单词

    <html>
        <head>
            <title>Number to word</title>

            <script>
                function toWords() {
                    var s = document.getElementById('value').value;
                    var th = ['','mille','million', 'milliard','billion'];
                    var dg = ['zéro','un','deux','trois','quatre', 'cinq','six','sept','huit','neuf'];
                    var tn = 

['dix','onze','douze','treize', 'quatorze','quinze','seize', 'dix-sept','dix-huit','dix-neuf'];
                var tw = ['vingt','trente','quarante','cinquante', 'soixante','soixante-dix','quatre-vingt','quatre-vingt-dix'];
                s = s.toString();
                s = s.replace(/[\, ]/g,'');
                if (s != parseFloat(s)) return 'not a number';
                var x = s.indexOf('.');
                if (x == -1)
                    x = s.length;
                if (x > 15)
                    return 'too big';
                var n = s.split(''); 
                var str = '';
                var sk = 0;
                for (var i=0;   i < x;  i++) {
                    if ((x-i)%3==2) { 
                        if (n[i] == '1') {

                            str += tn[Number(n[i+1])] + ' ';
                            i++;
                            sk=1;
                        } else if (n[i]!=0) { 
                            if(s!=21 && s!=31 && s!=41 && s!=51 && s!=61 && s!=71 && s!=72 && s!=73 && s!=74 && s!=75 && s!=76 && s!=100 && s!=91 && s!=92 && s!=93 && s!=94 && s!=95 && s!=96){
                            if(s==20 || s==30 || s==40 || s==50 || s==60 || s==70 || s==80 || s==90){
                            str += tw[n[i]-2] + ' ';} // for not to display hyphens for 20,30...90 
                            else{
                            str += tw[n[i]-2] + '-';}
                            sk=1;
                            }
                        }
                    } else if (n[i]!=0) {
                        if(s!=21 && s!=31 && s!=41 && s!=51 && s!=61 && s!=71 && s!=72 && s!=73 && s!=74 && s!=75 && s!=76 && s!=100 && s!=91 && s!=92 && s!=93 && s!=94 && s!=95 && s!=96){

                        str += dg[n[i]] +' ';
                        if ((x-i)%3==0) str += 'hundert ';  // for start from 101 - 

                        sk=1;
                        }
                    }
                    if ((x-i)%3==1) {
                        if(s!=21 && s!=31 && s!=41 && s!=51 && s!=61 && s!=71 && s!=72 && s!=73 && s!=74 && s!=75 && s!=76 && s!=100 && s!=91 && s!=92 && s!=93 && s!=94 && s!=95 && s!=96){
                        if (sk)
                            str += th[(x-i-1)/3] + ' ';
                        sk=0;
                        }
                    }
                }

                if (x != s.length) {
                    var y = s.length;
                    //str += 'point ';
                    //for (var i=x+1; i<y; i++)
                    //  str += dg[n[i]] +' ';
                    str += 'virgule ';
                     var counter=0;
                     for (var i=x+1; i<y; i++){
                        if ((y-i)%3==2) { 
                                            if (n[i] == '1') {
                                                            str += tn[Number(n[i+1])] + ' ';
                                                            i++;
                                                            counter=1;
                                            } else if (n[i]!=0) {
                                                            str += tw[n[i]-2] + '-';
                                                            counter=1;
                                            }
                                        }else if (n[i]!=0) { // 0235
                                            str += dg[n[i]] +' ';
                                        }
                     }

                }

                if (s!=21 && s!=31 && s!=41 && s!=51 && s!=61 && s!=71 && s!=72 && s!=73 && s!=74 && s!=75 && s!=76 && s!=100 && s!=91 && s!=92 && s!=93 && s!=94 && s!=95 && s!=96){
                document.getElementById("demo").innerHTML = str.replace(/\s+/g,' ')

                }
                else if (s==21){
                str = 'vingt-et-un'
                document.getElementById("demo").innerHTML = str;
                }//alert(str.replace(/\s+/g,' '));
                else if (s==31){
                str = 'trente-et-un'
                document.getElementById("demo").innerHTML = str;}
                else if (s==41){
                str = 'quarante-et-un'
                document.getElementById("demo").innerHTML = str;}
                else if (s==51){
                str = 'cinquante-et-un'
                document.getElementById("demo").innerHTML = str;}
                else if (s==61){
                str = 'soixante-et-un'
                document.getElementById("demo").innerHTML = str;}
                else if (s==71){
                str = 'soixante-et-onze'
                document.getElementById("demo").innerHTML = str;}
                else if (s==72){
                str = 'soixante-douze'
                document.getElementById("demo").innerHTML = str;}
                else if (s==73){
                str = 'soixante-treize'
                document.getElementById("demo").innerHTML = str;}
                else if (s==74){
                str = 'soixante-quatorze'
                document.getElementById("demo").innerHTML = str;}
                else if (s==75){
                str = 'soixante-quinze'
                document.getElementById("demo").innerHTML = str;}
                else if (s==76){
                str = 'soixante-seize'
                document.getElementById("demo").innerHTML = str;}
                else if (s==100){
                str = 'cent'
                document.getElementById("demo").innerHTML = str;}
                else if (s==91){
                str = 'quatre-vingt-onze'
                document.getElementById("demo").innerHTML = str;}
                else if (s==92){
                str = 'quatre-vingt-douze'
                document.getElementById("demo").innerHTML = str;}
                else if (s==93){
                str = 'quatre-vingt-treize'
                document.getElementById("demo").innerHTML = str;}
                else if (s==94){
                str = 'quatre-vingt-quatorze'
                document.getElementById("demo").innerHTML = str;}   
                else if (s==95){
                str = 'quatre-vingt-quinze'
                document.getElementById("demo").innerHTML = str;}   
                else if (s==96){
                str = 'quatre-vingt-seize'
                document.getElementById("demo").innerHTML = str;}               
            }
        </script>
    </head>
    <body>
        <p>Enter only numbers (max 15 digits) : </p>
        <input type="text" name="value" id='value' /><br>
        <input type="button" value="submit" onclick="toWords()" />
        <p id="demo"></p>
        <p id="demo1"></p>
    </body>
</html> 

答案 15 :(得分:0)

@pramod kharade 的回答

简化

function NumToWord(inputNumber) {
    var str = new String(inputNumber)
    var splt = str.split("");
    var rev = splt.reverse();
    var once = ['Zero', ' One', ' Two', ' Three', ' Four', ' Five', ' Six', ' Seven', ' Eight', ' Nine'];
    var twos = ['Ten', ' Eleven', ' Twelve', ' Thirteen', ' Fourteen', ' Fifteen', ' Sixteen', ' Seventeen', ' Eighteen', ' Nineteen'];
    var tens = ['', 'Ten', ' Twenty', ' Thirty', ' Forty', ' Fifty', ' Sixty', ' Seventy', ' Eighty', ' Ninety'];

    numLength = rev.length;
    var word = new Array();
    var j = 0;

    for (i = 0; i < numLength; i++) {
        switch (i) {

            case 0:
                if ((rev[i] == 0) || (rev[i + 1] == 1)) {
                    word[j] = '';
                }
                else {
                    word[j] = '' + once[rev[i]];
                }
                word[j] = word[j];
                break;

            case 1:
                aboveTens();
                break;

            case 2:
                if (rev[i] == 0) {
                    word[j] = '';
                }
                else if ((rev[i - 1] == 0) || (rev[i - 2] == 0)) {
                    word[j] = once[rev[i]] + " Hundred ";
                }
                else {
                    word[j] = once[rev[i]] + " Hundred and";
                }
                break;

            case 3:
                if (rev[i] == 0 || rev[i + 1] == 1) {
                    word[j] = '';
                }
                else {
                    word[j] = once[rev[i]];
                }
                if ((rev[i + 1] != 0) || (rev[i] > 0)) {
                    word[j] = word[j] + " Thousand";
                }
                break;

                
            case 4:
                aboveTens();
                break;

            case 5:
                if ((rev[i] == 0) || (rev[i + 1] == 1)) {
                    word[j] = '';
                }
                else {
                    word[j] = once[rev[i]];
                }
                if (rev[i + 1] !== '0' || rev[i] > '0') {
                    word[j] = word[j] + " Lakh";
                }
                 
                break;

            case 6:
                aboveTens();
                break;

            case 7:
                if ((rev[i] == 0) || (rev[i + 1] == 1)) {
                    word[j] = '';
                }
                else {
                    word[j] = once[rev[i]];
                }
                if (rev[i + 1] !== '0' || rev[i] > '0') {
                    word[j] = word[j] + " Crore";
                }                
                break;

            case 8:
                aboveTens();
                break;


            default: break;
        }
        j++;
    }

    function aboveTens() {
        if (rev[i] == 0) { word[j] = ''; }
        else if (rev[i] == 1) { word[j] = twos[rev[i - 1]]; }
        else { word[j] = tens[rev[i]]; }
    }

    word.reverse();
    var finalOutput = '';
    for (i = 0; i < numLength; i++) {
        finalOutput = finalOutput + word[i];
    }
return finalOutput;
}

console.log(NumToWord(123))
console.log(NumToWord(12345678))
console.log(NumToWord(12334543))
console.log(NumToWord(6789876123))

答案 16 :(得分:0)

我得到并使用的最简单的可能是 Ben E。我对他的代码进行了修改,因为当您尝试转换 500,000.00 时,它只会返回例如“五百”。我只是添加了一行条件代码来修复它。还增加了给出最后两位小数的规定。我现在使用它在打印支票时将金额转换为单词。这是我添加的修订版:

if (Math.floor((number%(100*Math.pow(1000,i))/Math.pow(1000,i))) == 0) {
    word = first[Math.floor(tempNumber/(100*Math.pow(1000,i)))] + 'Hundred ' + mad[i] 
        + ' ' + word;
} else {

我很难在此处粘贴代码,但如果您需要任何说明,请告诉我

答案 17 :(得分:0)

我修改了@ McShaman的代码,将其转换为CoffeeScript,并通过JSNice添加了文档。这是结果,对于那些感兴趣的人(英语):

###
    Convert an integer to an English string equivalent
    @param {Integer} number the integer to be converted
    @return {String} the English number equivalent
###
inWords = (number) ->
    ###
        @property {Array}
    ###
    englishIntegers = [
        ""
        "one "
        "two "
        "three "
        "four "
        "five "
        "six "
        "seven "
        "eight "
        "nine "
        "ten "
        "eleven "
        "twelve "
        "thirteen "
        "fourteen "
        "fifteen "
        "sixteen "
        "seventeen "
        "eighteen "
        "nineteen "
    ]

    ###
        @property {Array}
    ###
    englishIntegerTens = [
        ""
        ""
        "twenty"
        "thirty"
        "forty"
        "fifty"
        "sixty"
        "seventy"
        "eighty"
        "ninety"
    ]

    ###
        @property {Array}
    ###
    englishIntegerThousands = [
        "thousand"
        "million"
        ""
    ]
    number = number.toString()
    return "" if number.length > 9

    ###
        @property {string}
    ###
    number = ("000000000" + number).substr(-9)

    ###
      @property {(Array.<string>|null)}
      ###
    number = number.match(/.{3}/g)

    ###
        @property {string}
    ###
    convertedWords = ""

    ###
        @property {number}
    ###
    i = 0
    while i < englishIntegerThousands.length

        ###
            @property {string}
        ###
        currentNumber = number[i]

        ###
            @property {string}
        ###
        tempResult = ""
        tempResult += (if convertedWords isnt "" then " " + englishIntegerThousands[i] + " " else "")
        tempResult += (if currentNumber[0] isnt 0 then englishIntegers[Number(currentNumber[0])] + "hundred " else "")

        ###
            @property {string}
        ###
        currentNumber = currentNumber.substr(1)
        tempResult += (if currentNumber isnt 0 then ((if tempResult isnt "" then "and " else "")) + (englishIntegers[Number(currentNumber)] or englishIntegerTens[currentNumber[0]] + " " + englishIntegers[currentNumber[1]]) else "")
        convertedWords += tempResult
        i++
    convertedWords

答案 18 :(得分:0)

也适用于十进制值的函数

function amountToWords(amountInDigits){
    // American Numbering System
    var th = ['','thousand','million', 'billion','trillion'];

    var dg = ['zero','one','two','three','four', 'five','six','seven','eight','nine'];
    var tn = ['ten','eleven','twelve','thirteen', 'fourteen','fifteen','sixteen', 'seventeen','eighteen','nineteen'];
    var tw = ['twenty','thirty','forty','fifty', 'sixty','seventy','eighty','ninety'];
    function toWords(s){
      s = s.toString();
      s = s.replace(/[\, ]/g,'');
      if (s != parseFloat(s))
      return 'not a number';
      var x = s.indexOf('.');
      if (x == -1) x = s.length;
      if (x > 15) return 'too big';
      var n = s.split('');
      var str = '';
      var sk = 0;
      for (var i=0; i < x; i++){
        if ((x-i)%3==2){
          if (n[i] == '1') {
            str += tn[Number(n[i+1])] + ' ';
            i++; sk=1;
          } else if (n[i]!=0) {
              str += tw[n[i]-2] + ' ';sk=1;
            }
          } else if (n[i]!=0) {
            str += dg[n[i]] +' ';
            if ((x-i)%3==0)
            str += 'hundred ';
            sk=1;
          } if ((x-i)%3==1) {
            if (sk) str += th[(x-i-1)/3] + ' ';sk=0;
          }
        }
        if (x != s.length) {
          var y = s.length;
          str += 'point ';
          for (var i=x+1; i<y; i++) str += dg[n[i]] +' ';
        }
        return str.replace(/\s+/g,' ');
      }

      return toWords(amountInDigits);
  }
<input type="text" name="number" placeholder="Number OR Amount" onkeyup="word.innerHTML=amountToWords(this.value)" />
<div id="word"></div>

答案 19 :(得分:0)

想到的最干净,最简单的方法:

const numberText = {
  1: 'one',
  2: 'two',
  3: 'three',
  4: 'four',
  5: 'five',
  6: 'six',
  7: 'seven',
  8: 'eight',
  9: 'nine',
  10: 'ten',
  11: 'eleven',
  12: 'twelve',
  13: 'thirteen',
  14: 'fourteen',
  15: 'fifteen',
  16: 'sixteen',
  17: 'seventeen',
  18: 'eighteen',
  19: 'nineteen',
  20: 'twenty',
  30: 'thirty',
  40: 'forty',
  50: 'fifty',
  60: 'sixty',
  70: 'seventy',
  80: 'eighty',
  90: 'ninety',
  100: 'hundred',
  1000: 'thousand',
}

const numberValues = Object.keys(numberText)
  .map((val) => Number(val))
  .sort((a, b) => b - a)

const convertNumberToEnglishText = (n) => {
  if (n === 0) return 'zero'
  if (n < 0) return 'negative ' + convertNumberToEnglishText(-n)

  let num = n
  let text = ''

  for (const numberValue of numberValues) {
    const count = Math.trunc(num / numberValue)

    if (count < 1) continue

    if (numberValue >= 100) text += convertNumberToEnglishText(count) + ' '

    text += numberText[numberValue] + ' '
    num -= count * numberValue
  }

  if (num !== 0) throw Error('Something went wrong!')

  return text.trim()
}

答案 20 :(得分:0)

对于那些寻求英式/英文命名约定的人。

基于@Salman的answer

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'];

function inWords (num) {
    if ((num = num.toString()).length > 12) return 'overflow';
    n = ('00000000000' + num).substr(-12).match(/^(\d{3})(\d{3})(\d{3})(\d{1})(\d{2})$/);
    if (!n) return; var str = '';
    str += (n[1] != 0) ? (Number(n[1]) > 99 ? this.a[Number(n[1][0])] + 'hundred ' : '') + (a[Number(n[1])] || b[n[1][1]] + ' ' + a[n[1][2]]) + 'billion ' : '';
    str += (n[2] != 0) ? (Number(n[2]) > 99 ? this.a[Number(n[2][0])] + 'hundred ' : '') + (a[Number(n[2])] || b[n[2][1]] + ' ' + a[n[2][2]]) + 'million ' : '';
    str += (n[3] != 0) ? (Number(n[3]) > 99 ? this.a[Number(n[3][0])] + 'hundred ' : '') + (a[Number(n[3])] || b[n[3][1]] + ' ' + a[n[3][2]]) + 'thousand ' : '';
    str += (n[4] != 0) ? (a[Number(n[4])] || b[n[4][0]] + ' ' + a[n[4][1]]) + 'hundred ' : '';
     str += (Number(n[5]) !== 0) ? ((str !== '') ? 'and ' : '') +
                (this.a[Number(n[5])] || this.b[n[5][0]] + ' ' +
                    this.a[n[5][1]]) + '' : '';
    return str;
}

document.getElementById('number').onkeyup = function () {
    document.getElementById('words').innerHTML = inWords(document.getElementById('number').value);
};
<span id="words"></span>
<input id="number" type="text" />

答案 21 :(得分:0)

    function numberToEnglish( n ) {
        
        var string = n.toString(), units, tens, scales, start, end, chunks, chunksLen, chunk, ints, i, word, words, and = 'and';

        /* Remove spaces and commas */
        string = string.replace(/[, ]/g,"");

        /* Is number zero? */
        if( parseInt( string ) === 0 ) {
            return 'zero';
        }
        
        /* Array of units as words */
        units = [ '', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten', 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen' ];
        
        /* Array of tens as words */
        tens = [ '', '', 'twenty', 'thirty', 'forty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety' ];
        
        /* Array of scales as words */
        scales = [ '', 'thousand', 'million', 'billion', 'trillion', 'quadrillion', 'quintillion', 'sextillion', 'septillion', 'octillion', 'nonillion', 'decillion', 'undecillion', 'duodecillion', 'tredecillion', 'quatttuor-decillion', 'quindecillion', 'sexdecillion', 'septen-decillion', 'octodecillion', 'novemdecillion', 'vigintillion', 'centillion' ];
        
        /* Split user argument into 3 digit chunks from right to left */
        start = string.length;
        chunks = [];
        while( start > 0 ) {
            end = start;
            chunks.push( string.slice( ( start = Math.max( 0, start - 3 ) ), end ) );
        }
        
        /* Check if function has enough scale words to be able to stringify the user argument */
        chunksLen = chunks.length;
        if( chunksLen > scales.length ) {
            return '';
        }
        
        /* Stringify each integer in each chunk */
        words = [];
        for( i = 0; i < chunksLen; i++ ) {
            
            chunk = parseInt( chunks[i] );
            
            if( chunk ) {
                
                /* Split chunk into array of individual integers */
                ints = chunks[i].split( '' ).reverse().map( parseFloat );
            
                /* If tens integer is 1, i.e. 10, then add 10 to units integer */
                if( ints[1] === 1 ) {
                    ints[0] += 10;
                }
                
                /* Add scale word if chunk is not zero and array item exists */
                if( ( word = scales[i] ) ) {
                    words.push( word );
                }
                
                /* Add unit word if array item exists */
                if( ( word = units[ ints[0] ] ) ) {
                    words.push( word );
                }
                
                /* Add tens word if array item exists */
                if( ( word = tens[ ints[1] ] ) ) {
                    words.push( word );
                }
                
                /* Add 'and' string after units or tens integer if: */
                if( ints[0] || ints[1] ) {
                    
                    /* Chunk has a hundreds integer or chunk is the first of multiple chunks */
                    if( ints[2] || ! i && chunksLen ) {
                        words.push( and );
                    }
                
                }
                
                /* Add hundreds word if array item exists */
                if( ( word = units[ ints[2] ] ) ) {
                    words.push( word + ' hundred' );
                }
                
            }
            
        }
        
        return words.reverse().join( ' ' );
        
    }


// - - - - - Tests - - - - - -
function test(v) {
  var sep = ('string'==typeof v)?'"':'';
  console.log("numberToEnglish("+sep + v.toString() + sep+") = "+numberToEnglish(v));
}
test(2);
test(721);
test(13463);
test(1000001);
test("21,683,200,000,621,384");

答案 22 :(得分:0)

我的解决方案基于胡安·盖坦(JuanGaitán)的印度货币解决方案,最多可以解决上千亿美元的问题。

function valueInWords(value) {
    let ones = ['', 'one', 'two', 'three', 'four',
            'five', 'six', 'seven', 'eight', 'nine',
            'ten', 'eleven', 'twelve', 'thirteen', 'fourteen',
            'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen'];   
    let tens = ['twenty','thirty', 'forty','fifty', 'sixty', 'seventy', 'eighty', 'ninety'];
    let digit = 0;   
    if (value < 20) return ones[value];   
    if (value < 100) {     
        digit = value % 10; //remainder     
        return tens[Math.floor(value/10)-2] + " " + (digit > 0 ? ones[digit] : "");   
    }
    if (value < 1000) {    
         return ones[Math.floor(value/100)] + " hundred " + (value % 100 > 0 ? valueInWords(value % 100) : "");   
    }   
    if (value < 100000) {     
        return valueInWords(Math.floor(value/1000)) + " thousand " + (value % 1000 > 0 ? valueInWords(value % 1000) : "");   
    }   
    if (value < 10000000) {     
        return valueInWords(Math.floor(value/100000)) + " lakh " + (value % 100000 > 0 ? valueInWords(value % 100000) : "");   
    }   
    return valueInWords(Math.floor(value/10000000)) + " crore " + (value % 10000000 > 0 ? valueInWords(value % 10000000) : ""); 
}

答案 23 :(得分:0)

我创建了自定义函数// Retrieving view's item LinearLayout linear = findViewById(R.id.linear_layout_existing_picto); // Retrieving fields from R.drawable Field[] fields = R.drawable.class.getFields(); // Sorting drawables by name and inserting into the scrollView for (final Field field : fields) { try { if (field.getName().startsWith("dra_")) { int currentResId = field.getInt(R.drawable.class); ImageButton imageButtonDrawable = (ImageButton) getLayoutInflater().inflate(R.layout.template_drawable, null); imageButtonDrawable.setImageResource(currentResId); imageButtonDrawable.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(); intent.putExtra("result", field.getName()); setResult(AddExistingPictoActivity.RESULT_OK, intent); finish(); } }); linear.addView(imageButtonDrawable); } } catch (IllegalAccessException e) { e.printStackTrace(); } } ,可以将数字转换为单词

ntsConvert()

答案 24 :(得分:0)

虽然该系统确实使用了for循环,但它使用的是美式英语,并且快速,准确且可扩展(您可以将无限值添加到“ th”变量中,并将其包括在内)。

此函数向后捕获3组数字,因此它可以获取,通常以数字形式将其分开的数字组。然后,将每组三个数字添加到仅具有三个数字(例如:123)的单词形式的数组中。然后,它获取新的数组列表,并再次反转它,同时将相同索引的th var添加到字符串的末尾。

var ones = ['','one ','two ','three ','four ', 'five ','six ','seven ','eight ','nine ','ten ','eleven ','twelve ','thirteen ','fourteen ','fifteen ','sixteen ','seventeen ','eighteen ','nineteen '];
var tens = ['', '', 'twenty ','thirty ','forty ','fifty ', 'sixty ','seventy ','eighty ','ninety ', 'hundred '];
var th = ['', 'thousand ','million ','billion ', 'trillion '];

function numberToWord(number){
  var text = "";
  var size = number.length;

  var textList = [];
  var textListCount = 0;

  //get each 3 digit numbers
  for(var i = number.length-1; i >= 0; i -= 3){
    //get 3 digit group
    var num = 0;
    if(number[(i-2)]){num += number[(i-2)];}
    if(number[(i-1)]){num += number[(i-1)];}
    if(number[i]){num += number[i];}

    //remove any extra 0's from begining of number
    num = Math.floor(num).toString();

    if(num.length == 1 || num < 20){
      //if one digit or less than 20
      textList[textListCount] = ones[num];
    }else if(num.length == 2){
      //if 2 digits and greater than 20
      textList[textListCount] = tens[num[0]]+ones[num[1]];
    }else if(num.length == 3){
      //if 3 digits
      textList[textListCount] = ones[num[0]]+tens[10]+tens[num[1]]+ones[num[2]];
    }

    textListCount++;

  }

  //add the list of 3 digit groups to the string
  for(var i = textList.length-1; i >= 0; i--){
    if(textList[i] !== ''){text += textList[i]+th[i];} //skip if the number was 0
  }

  return text;
}

答案 25 :(得分:0)

您可以从github查看我的版本。这不是那么难的方式。我测试了0到9999之间的数字,但如果你想digits to words

你可以扩展数组

答案 26 :(得分:0)

我刚刚写了paisa.js来做这件事,它也能正确处理十万分之一和百万分之一,可以检查出来。核心看起来有点像这样:

const regulars = [
  {
    1: 'one', 2: 'two', 3: 'three', 4: 'four', 5: 'five', 6: 'six', 7: 'seven', 8: 'eight', 9: 'nine'
  },
  {
    2: 'twenty', 3: 'thirty', 4: 'forty', 5: 'fifty', 6: 'sixty', 7: 'seventy', 8: 'eighty', 9: 'ninety'
  }
]

const exceptions = {
  10: 'ten',
  11: 'eleven',
  12: 'twelve',
  13: 'thirteen',
  14: 'fourteen',
  15: 'fifteen',
  16: 'sixteen',
  17: 'seventeen',
  18: 'eighteen',
  19: 'nineteen'
}

const partInWords = (part) => {
  if (parseInt(part) === 0) return
  const digits = part.split('')
  const words = []
  if (digits.length === 3) {
    words.push([regulars[0][digits.shift()], 'hundred'].join(' '))
  }
  if (exceptions[digits.join('')]) {
    words.push(exceptions[digits.join('')])
  } else {
    words.push(digits.reverse().reduce((memo, el, i) => {
      memo.unshift(regulars[i][el])
      return memo
    }, []).filter(w => w).join(' '))
  }
  return words.filter(w => w.trim().length).join(' and ')
}

答案 27 :(得分:0)

尽管如此,这个问题已经得到了解答 - 我仍然希望分享我最近在java脚本中开发的内容(基于我在Internet上找到的旧C#.Net实现的逻辑),用于将印度货币值转换为Words。它最多可以处理40位数字。你可以看看。

使用方法:     InrToWordConverter.Initialize();.     var inWords = InrToWordConverter.ConvertToWord(amount);

实现:

htPunctuation = {};
listStaticSuffix = {};
listStaticPrefix = {};
listHelpNotation = {};

var InrToWordConverter = function () {

};

InrToWordConverter.Initialize = function () {
    InrToWordConverter.LoadStaticPrefix();
    InrToWordConverter.LoadStaticSuffix();
    InrToWordConverter.LoadHelpofNotation();
};

InrToWordConverter.ConvertToWord = function (value) {
    value = value.toString();

    if (value) {
        var tokens = value.split(".");
        var rsPart = "";
        var psPart = "";
        if (tokens.length === 2) {
            rsPart = String.trim(tokens[0]) || "0";
            psPart = String.trim(tokens[1]) || "0";
        }
        else if (tokens.length === 1) {
            rsPart = String.trim(tokens[0]) || "0";
            psPart = "0";
        }
        else {
            rsPart = "0";
            psPart = "0";
        }

        htPunctuation = {};
        var rsInWords = InrToWordConverter.ConvertToWordInternal(rsPart) || "Zero";
        var psInWords = InrToWordConverter.ConvertToWordInternal(psPart) || "Zero";

        var result = "Rupees " + rsInWords + "and " + psInWords + " Paise.";
        return result;
    }
};

InrToWordConverter.ConvertToWordInternal = function (value) {
    var convertedString = "";
    if (!(value.toString().length > 40))
    {
        if (InrToWordConverter.IsNumeric(value.toString()))
        {
            try
            {
                var strValue = InrToWordConverter.Reverse(value);
                switch (strValue.length)
                {
                    case 1:
                        if (parseInt(strValue.toString()) > 0) {
                            convertedString = InrToWordConverter.GetWordConversion(value);
                        }
                        else {
                            convertedString = "Zero ";
                        }
                        break;
                    case 2:
                        convertedString = InrToWordConverter.GetWordConversion(value);
                        break;
                    default:
                        InrToWordConverter.InsertToPunctuationTable(strValue);
                        InrToWordConverter.ReverseHashTable();
                        convertedString = InrToWordConverter.ReturnHashtableValue();
                        break;
                }
            }
            catch (exception) {
                convertedString = "Unexpected Error Occured <br/>";
            }
        }
        else {
            convertedString = "Please Enter Numbers Only, Decimal Values Are not supported";
        }
    }
    else {
        convertedString = "Please Enter Value in Less Then or Equal to 40 Digit";
    }
    return convertedString;
};

InrToWordConverter.IsNumeric = function (valueInNumeric) {
    var isFine = true;
    valueInNumeric = valueInNumeric || "";
    var len = valueInNumeric.length;
    for (var i = 0; i < len; i++) {
        var ch = valueInNumeric[i];
        if (!(ch >= '0' && ch <= '9')) {
            isFine = false;
            break;
        }
    }
    return isFine;
};

InrToWordConverter.ReturnHashtableValue = function () {
    var strFinalString = "";
    var keysArr = [];
    for (var key in htPunctuation) {
        keysArr.push(key);
    }
    for (var i = keysArr.length - 1; i >= 0; i--) {
        var hKey = keysArr[i];
        if (InrToWordConverter.GetWordConversion((htPunctuation[hKey]).toString()) !== "") {
            strFinalString = strFinalString + InrToWordConverter.GetWordConversion((htPunctuation[hKey]).toString()) + InrToWordConverter.StaticPrefixFind((hKey).toString());
        }
    }
    return strFinalString;
};

InrToWordConverter.ReverseHashTable = function () {
    var htTemp = {};
    for (var key in htPunctuation) {
        var item = htPunctuation[key];
        htTemp[key] = InrToWordConverter.Reverse(item.toString());
    }
    htPunctuation = {};
    htPunctuation = htTemp;
};

InrToWordConverter.InsertToPunctuationTable = function (strValue) {
    htPunctuation[1] = strValue.substr(0, 3).toString();
    var j = 2;
    for (var i = 3; i < strValue.length; i = i + 2) {
        if (strValue.substr(i).length > 0) {
            if (strValue.substr(i).length >= 2) {
                htPunctuation[j] = strValue.substr(i, 2).toString();
            }
            else {
                htPunctuation[j] = strValue.substr(i, 1).toString();
            }
        }
        else {
            break;
        }
        j++;

    }
};

InrToWordConverter.Reverse = function (strValue) {
    var reversed = "";
    for (var i in strValue) {
        var ch = strValue[i];
        reversed = ch + reversed;
    }
    return reversed;
};

InrToWordConverter.GetWordConversion = function (inputNumber) {
    var toReturnWord = "";
    if (inputNumber.length <= 3 && inputNumber.length > 0) {
        if (inputNumber.length === 3) {
            if (parseInt(inputNumber.substr(0, 1)) > 0) {
                toReturnWord = toReturnWord + InrToWordConverter.StaticSuffixFind(inputNumber.substr(0, 1)) + "Hundred ";
            }

            var tempString = InrToWordConverter.StaticSuffixFind(inputNumber.substr(1, 2));

            if (tempString === "")
            {
                toReturnWord = toReturnWord + InrToWordConverter.StaticSuffixFind(inputNumber.substr(1, 1) + "0");
                toReturnWord = toReturnWord + InrToWordConverter.StaticSuffixFind(inputNumber.substr(2, 1));
            }
            toReturnWord = toReturnWord + tempString;
        }
        if (inputNumber.length === 2)
        {
            var tempString = InrToWordConverter.StaticSuffixFind(inputNumber.substr(0, 2));
            if (tempString === "")
            {
                toReturnWord = toReturnWord + InrToWordConverter.StaticSuffixFind(inputNumber.substr(0, 1) + "0");
                toReturnWord = toReturnWord + InrToWordConverter.StaticSuffixFind(inputNumber.substr(1, 1));
            }
            toReturnWord = toReturnWord + tempString;
        }
        if (inputNumber.length === 1)
        {
            toReturnWord = toReturnWord + InrToWordConverter.StaticSuffixFind(inputNumber.substr(0, 1));
        }

    }
    return toReturnWord;
};

InrToWordConverter.StaticSuffixFind = function (numberKey) {
    var valueFromNumber = "";
    for (var key in listStaticSuffix) {
        if (String.trim(key.toString()) === String.trim(numberKey)) {
            valueFromNumber = listStaticSuffix[key].toString();
            break;
        }
    }
    return valueFromNumber;
};

InrToWordConverter.StaticPrefixFind = function (numberKey) {
    var valueFromNumber = "";
    for (var key in listStaticPrefix) {
        if (String.trim(key) === String.trim(numberKey)) {
            valueFromNumber = listStaticPrefix[key].toString();
            break;
        }
    }
    return valueFromNumber;
};

InrToWordConverter.StaticHelpNotationFind = function (numberKey) {
    var helpText = "";
    for (var key in listHelpNotation) {
        if (String.trim(key.toString()) === String.trim(numberKey)) {
            helpText = listHelpNotation[key].toString();
            break;
        }
    }
    return helpText;
};

InrToWordConverter.LoadStaticPrefix = function () {
    listStaticPrefix[2] = "Thousand ";
    listStaticPrefix[3] = "Lac ";
    listStaticPrefix[4] = "Crore ";
    listStaticPrefix[5] = "Arab ";
    listStaticPrefix[6] = "Kharab ";
    listStaticPrefix[7] = "Neel ";
    listStaticPrefix[8] = "Padma ";
    listStaticPrefix[9] = "Shankh ";
    listStaticPrefix[10] = "Maha-shankh ";
    listStaticPrefix[11] = "Ank ";
    listStaticPrefix[12] = "Jald ";
    listStaticPrefix[13] = "Madh ";
    listStaticPrefix[14] = "Paraardha ";
    listStaticPrefix[15] = "Ant ";
    listStaticPrefix[16] = "Maha-ant ";
    listStaticPrefix[17] = "Shisht ";
    listStaticPrefix[18] = "Singhar ";
    listStaticPrefix[19] = "Maha-singhar ";
    listStaticPrefix[20] = "Adant-singhar ";
};

InrToWordConverter.LoadStaticSuffix = function () {
    listStaticSuffix[1] = "One ";
    listStaticSuffix[2] = "Two ";
    listStaticSuffix[3] = "Three ";
    listStaticSuffix[4] = "Four ";
    listStaticSuffix[5] = "Five ";
    listStaticSuffix[6] = "Six ";
    listStaticSuffix[7] = "Seven ";
    listStaticSuffix[8] = "Eight ";
    listStaticSuffix[9] = "Nine ";
    listStaticSuffix[10] = "Ten ";
    listStaticSuffix[11] = "Eleven ";
    listStaticSuffix[12] = "Twelve ";
    listStaticSuffix[13] = "Thirteen ";
    listStaticSuffix[14] = "Fourteen ";
    listStaticSuffix[15] = "Fifteen ";
    listStaticSuffix[16] = "Sixteen ";
    listStaticSuffix[17] = "Seventeen ";
    listStaticSuffix[18] = "Eighteen ";
    listStaticSuffix[19] = "Nineteen ";
    listStaticSuffix[20] = "Twenty ";
    listStaticSuffix[30] = "Thirty ";
    listStaticSuffix[40] = "Fourty ";
    listStaticSuffix[50] = "Fifty ";
    listStaticSuffix[60] = "Sixty ";
    listStaticSuffix[70] = "Seventy ";
    listStaticSuffix[80] = "Eighty ";
    listStaticSuffix[90] = "Ninty ";
};

InrToWordConverter.LoadHelpofNotation = function () {
    listHelpNotation[2] = "=1,000 (3 Trailing Zeros)";
    listHelpNotation[3] = "=1,00,000 (5 Trailing Zeros)";
    listHelpNotation[4] = "=1,00,00,000 (7 Trailing Zeros)";
    listHelpNotation[5] = "=1,00,00,00,000 (9 Trailing Zeros)";
    listHelpNotation[6] = "=1,00,00,00,00,000 (11 Trailing Zeros)";
    listHelpNotation[7] = "=1,00,00,00,00,00,000 (13 Trailing Zeros)";
    listHelpNotation[8] = "=1,00,00,00,00,00,00,000 (15 Trailing Zeros)";
    listHelpNotation[9] = "=1,00,00,00,00,00,00,00,000 (17 Trailing Zeros)";
    listHelpNotation[10] = "=1,00,00,00,00,00,00,00,00,000 (19 Trailing Zeros)";
    listHelpNotation[11] = "=1,00,00,00,00,00,00,00,00,00,000 (21 Trailing Zeros)";
    listHelpNotation[12] = "=1,00,00,00,00,00,00,00,00,00,00,000 (23 Trailing Zeros)";
    listHelpNotation[13] = "=1,00,00,00,00,00,00,00,00,00,00,00,000 (25 Trailing Zeros)";
    listHelpNotation[14] = "=1,00,00,00,00,00,00,00,00,00,00,00,00,000 (27 Trailing Zeros)";
    listHelpNotation[15] = "=1,00,00,00,00,00,00,00,00,00,00,00,00,00,000 (29 Trailing Zeros)";
    listHelpNotation[16] = "=1,00,00,00,00,00,00,00,00,00,00,00,00,00,00,000 (31 Trailing Zeros)";
    listHelpNotation[17] = "=1,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,000 (33 Trailing Zeros)";
    listHelpNotation[18] = "=1,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,000 (35 Trailing Zeros)";
    listHelpNotation[19] = "=1,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,000 (37 Trailing Zeros)";
    listHelpNotation[20] = "=1,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,000 (39 Trailing Zeros)";
};
    if (!String.trim) {
    String.trim = function (str) {
        var result = "";
        var firstNonWhiteSpaceFound = false;
        var startIndex = -1;
        var endIndex = -1;
        if (str) {
            for (var i = 0; i < str.length; i++) {
                if (firstNonWhiteSpaceFound === false) {
                    if (str[i] === ' ' || str[i] === '\t') {
                        continue;
                    }
                    else {
                        firstNonWhiteSpaceFound = true;
                        startIndex = i;
                        endIndex = i;
                    }
                }
                else {
                    if (str[i] === ' ' || str[i] === '\t') {
                        continue;
                    }
                    else {
                        endIndex = i;
                    }
                }
            }
            if (startIndex !== -1 && endIndex !== -1) {
                result = str.slice(startIndex, endIndex + 1);
            }
        }
        return result;
    };
}

答案 28 :(得分:0)

这也是对naomik's excellent post的回应!不幸的是,我没有让代表在正确的位置发帖,但我把它放在这里以防它可以帮助任何人。

如果您需要英式英语书面形式,您需要对代码进行一些调整。英国英语在某些方面与美国不同。基本上你需要输入单词&#39;和&#39;在两个特定的地方。

  1. 一百个假设有十个和一个。例如,一百零一。一千一十七。 一千一百。
  2. 在某些边缘,经过一千,一百万,十亿等。当没有较小的单位时。例如。一千一十。一百四十四。 一百万和一千。
  3. 第一种情况可以通过检查makeGroup方法中的10和1并附加&#39;和&#39;来解决。当它们存在时。

    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('');
    

    };

    第二种情况比较复杂。它相当于

    • 添加&#39;和&#39;百万,一千,十亿,十亿,百万,百万,百万,百万,百万,百万,百万如果倒数第二个数字为零。 e.g。

    1,100, 0 57百万百五十七。 5,000, 0 06五百万&

    我认为这可以通过使用过滤功能在@ naomik的代码中实现,但我无法弄清楚如何。最后,我决定通过返回的返回数组循环,并使用indexOf查找单词“&#39; 100”的实例。在最后一个元素中缺失。

答案 29 :(得分:0)

以下是

的翻译
  • 整数到单词
  • 浮动到单词
  • 钱到字

测试用例位于底部

&#13;
&#13;
var ONE_THOUSAND = Math.pow(10, 3);
var ONE_MILLION = Math.pow(10, 6);
var ONE_BILLION = Math.pow(10, 9);
var ONE_TRILLION = Math.pow(10, 12);
var ONE_QUADRILLION = Math.pow(10, 15);
var ONE_QUINTILLION = Math.pow(10, 18);

function integerToWord(integer) {
  var prefix = '';
  var suffix = '';

  if (!integer){ return "zero"; }
  
  if(integer < 0){
    prefix = "negative";
    suffix = integerToWord(-1 * integer);
    return prefix + " " + suffix;
  }
  if(integer <= 90){
    switch (integer) {
      case integer < 0:
        prefix = "negative";
        suffix = integerToWord(-1 * integer);
        return prefix + " "  + suffix;
      case 1: return "one";
      case 2: return "two";
      case 3: return "three";
      case 4:  return "four";
      case 5: return "five";
      case 6: return "six";
      case 7: return "seven";
      case 8: return "eight";
      case 9: return "nine";
      case 10: return "ten";
      case 11: return "eleven";
      case 12: return "twelve";
      case 13: return "thirteen";
      case 14: return "fourteen";
      case 15: return "fifteen";
      case 16: return "sixteen";
      case 17: return "seventeen";
      case 18: return "eighteen";
      case 19: return "nineteen";
      case 20: return "twenty";
      case 30: return "thirty";
      case 40: return "forty";
      case 50: return "fifty";
      case 60: return "sixty";
      case 70: return "seventy";
      case 80: return "eighty";
      case 90: return "ninety";
      default: break;
    }
  }

  if(integer < 100){
    prefix = integerToWord(integer - integer % 10);
    suffix = integerToWord(integer % 10);
    return prefix + "-"  + suffix;
  }

  if(integer < ONE_THOUSAND){
    prefix = integerToWord(parseInt(Math.floor(integer / 100), 10) )  + " hundred";
    if (integer % 100){ suffix = " and "  + integerToWord(integer % 100); }
    return prefix + suffix;
  }

  if(integer < ONE_MILLION){
    prefix = integerToWord(parseInt(Math.floor(integer / ONE_THOUSAND), 10))  + " thousand";
    if (integer % ONE_THOUSAND){ suffix = integerToWord(integer % ONE_THOUSAND); }
  }
  else if(integer < ONE_BILLION){
    prefix = integerToWord(parseInt(Math.floor(integer / ONE_MILLION), 10))  + " million";
    if (integer % ONE_MILLION){ suffix = integerToWord(integer % ONE_MILLION); }
  }
  else if(integer < ONE_TRILLION){
    prefix = integerToWord(parseInt(Math.floor(integer / ONE_BILLION), 10))  + " billion";
    if (integer % ONE_BILLION){ suffix = integerToWord(integer % ONE_BILLION); }
  }
  else if(integer < ONE_QUADRILLION){
    prefix = integerToWord(parseInt(Math.floor(integer / ONE_TRILLION), 10))  + " trillion";
    if (integer % ONE_TRILLION){ suffix = integerToWord(integer % ONE_TRILLION); }
  }
  else if(integer < ONE_QUINTILLION){
    prefix = integerToWord(parseInt(Math.floor(integer / ONE_QUADRILLION), 10))  + " quadrillion";
    if (integer % ONE_QUADRILLION){ suffix = integerToWord(integer % ONE_QUADRILLION); }
  } else {
    return '';
  }
  return prefix + " "  + suffix;
}

function moneyToWord(value){
  var decimalValue = (value % 1);
  var integer = value - decimalValue;
  decimalValue = Math.round(decimalValue * 100);
  var decimalText = !decimalValue? '': integerToWord(decimalValue) + ' cent' + (decimalValue === 1? '': 's');
  var integerText= !integer? '': integerToWord(integer) + ' dollar' + (integer === 1? '': 's');
  return (
    integer && !decimalValue? integerText:
    integer && decimalValue? integerText + ' and ' + decimalText:
    !integer && decimalValue? decimalText:
    'zero cents'
  );
}

function floatToWord(value){
  var decimalValue = (value % 1);
  var integer = value - decimalValue;
  decimalValue = Math.round(decimalValue * 100);
  var decimalText = !decimalValue? '':
    decimalValue < 10? "point o' " + integerToWord(decimalValue):
    decimalValue % 10 === 0? 'point ' + integerToWord(decimalValue / 10):
    'point ' + integerToWord(decimalValue);
  return (
    integer && !decimalValue? integerToWord(integer):
    integer && decimalValue? [integerToWord(integer),  decimalText].join(' '):
    !integer && decimalValue? decimalText:
    integerToWord(0)
  );
}

// test
(function(){
  console.log('integerToWord ==================================');
  for(var i = 0; i < 101; ++i){
    console.log('%s=%s', i, integerToWord(i));
  }
  console.log('floatToWord ====================================');
  i = 131;
  while(i--){
    console.log('%s=%s', i / 100, floatToWord(i / 100));
  }
  console.log('moneyToWord ====================================');
  for(i = 0; i < 131; ++i){
    console.log('%s=%s', i / 100, moneyToWord(i / 100));
  }
}());
&#13;
&#13;
&#13;

答案 30 :(得分:-1)

 var units = ["", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"];
var tens = ["", "", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"];



function convert7digitIntoWords(num) {
    var remainder = num % 1000000
    var hun = num - remainder;
    var div = Math.floor(num / 100000);
    if (remainder !== 0)
        return (convert2digitIntoWords(div) + " lakhs " + convert5digitIntoWords(remainder % 100000))
    else
        return (convert2digitIntoWords(div) + " lakhs ")
}

function convert6digitIntoWords(num) {
    var remainder = num % 100000
    var hun = num - remainder;
    var div = Math.floor(num / 100000);
    if (remainder !== 0)
        return (units[div] + " lakh " + convert5digitIntoWords(remainder))
    else
        return (units[div] + " lakh ")
}

function convert5digitIntoWords(num) {
    var remainder = num % 10000
    var hun = num - remainder;
    var div = Math.floor(num / 1000);
    if (remainder !== 0)
        return (convert2digitIntoWords(div) + " thousand " + convert3digitIntoWords(remainder % 1000))
    else
        return (convert2digitIntoWords(div) + " thousand")
}

function convert4digitIntoWords(num) {
    var remainder = num % 1000
    var hun = num - remainder;
    var div = Math.floor(num / 1000);
    if (remainder !== 0)
        return (units[div] + " thousand " + convert3digitIntoWords(remainder))
    else
        return (units[div] + " thousand")
}


function convert3digitIntoWords(num) {
    var remainder = num % 100
    var hun = num - remainder;
    var div = Math.floor(num / 100);
    if (remainder !== 0)
        return (units[div] + " hundred " + convert2digitIntoWords(remainder))
    else
        return (units[div] + " hundred ")
}

function convert2digitIntoWords(num) {
    var remainder = num % 10;
    var div = Math.floor(num / 10);
    return (tens[div] + " " + convertNumIntoWords(remainder));
}

function convertNumIntoWords(num) {

    switch (("" + num).length) {
        case 1:
            return units[num];
        case 2:
            return convert2digitIntoWords(num);
        case 3:
            return convert3digitIntoWords(num)
        case 4:
            return convert4digitIntoWords(num)
        case 5:
            return convert5digitIntoWords(num)
        case 6:
            return convert6digitIntoWords(num)
        case 7:
            return convert7digitIntoWords(num)
        default:
            return "cannot be converted"
    }
}

console.log(convertNumIntoWords(3445125));

答案 31 :(得分:-2)

使用符合土耳其货币的JavaScript

尝试此代码
function dene() {
         var inpt = document.getElementById("tar1").value;
         var spt = inpt.split('');
         spt.reverse();

         var tek = ["", "Bir", "İki", "Üç", "Dört", "Beş", "Altı", "Yedi", "Sekiz", "Dokuz"];
         var onlu = ["", "On", "Yirmi", "Otuz", "Kırk", "Elli", "Atmış", "Yetmiş", "Seksen", "Doksan"];
         var Yuz = ["", "Yüz", "İkiYüz", "Üçyüz", "DörtYüz", "BeşYüz", "AltıYüz", "YediYüz", "SekizYüz", "DokuzYüz"];
         var ska = ["", "", "", "", "Bin", "Milyon", "Milyar", "Trilyon", "Katrilyon", "Kentilyon"];
         var i, j;
         var bas3 = "";
         var bas6 = "";
         var bas9 = "";
         var bas12 = "";
         var total;

               for(i = 0; i < 1; i++) {

                      bas3 += Yuz[spt[i+2]] + onlu[spt[i+1]] + tek[spt[i]];
                      bas6 += Yuz[spt[i+5]] + onlu[spt[i+4]] + tek[spt[i+3]] + ska[4];
                      bas9 += Yuz[spt[i+8]] + onlu[spt[i+7]] + tek[spt[i+6]] + ska[5];
                      bas12 += Yuz[spt[i+11]] + onlu[spt[i+10]] + tek[spt[i+9]] + ska[6];


                   if(inpt.length < 4) {
                       bas6 = '';
                       bas9 = '';
                   }
                   if(inpt.length > 6 && inpt.slice(5, 6) == 0) {
                     bas6 = bas6.replace(/Bin/g, '');
                   }
                   if(inpt.length < 7) {
                       bas9 = '';
                   } 
                   if(inpt.length > 9 && inpt.slice(1,3) == 000){
                       bas9 = bas9.replace(/Milyon/g, '');
                   }

                   if(inpt.length < 10) {
                    bas12 = '';
                 }
             }

         total = bas12 + bas9 + bas6 + bas3;
         total = total.replace(NaN, '');
         total = total.replace(undefined, '');

        document.getElementById('demo').innerHTML = 
            total;


     }