JavaScript 数字到单词

2024-02-21

例如,我正在尝试将数字转换为英语单词1234会成为: ”一千二百三十四".

我的策略是这样的:

  • 将数字分成三位并将它们放入数组(finlOutPut),从右到左。

  • 转换每个组(每个单元格中finlOutPut数组)的三个数字到一个单词(这就是triConvert函数确实)。如果所有三位数字都为零,则将它们转换为"dontAddBigSuffix"

  • 从右向左添加千、万、亿等。如果finlOutPut单元格等于"dontAddBigSufix"(因为它只是零),不要添加该单词并将单元格设置为" "(没有什么)。

它似乎工作得很好,但我在处理 19000000 这样的数字时遇到了一些问题9, 转换成: ”一亿九千万”。当有几个零时,它会以某种方式“忘记”最后的数字。

我做错了什么?错误在哪里?为什么它不能完美工作?

function update(){
    var bigNumArry = new Array('', ' thousand', ' million', ' billion', ' trillion', ' quadrillion', ' quintillion');

    var output = '';
    var numString =   document.getElementById('number').value;
    var finlOutPut = new Array();

    if (numString == '0') {
        document.getElementById('container').innerHTML = 'Zero';
        return;
    }

    if (numString == 0) {
        document.getElementById('container').innerHTML = 'messeg tell to enter numbers';
        return;
    }

    var i = numString.length;
    i = i - 1;

    //cut the number to grups of three digits and add them to the Arry
    while (numString.length > 3) {
        var triDig = new Array(3);
        triDig[2] = numString.charAt(numString.length - 1);
        triDig[1] = numString.charAt(numString.length - 2);
        triDig[0] = numString.charAt(numString.length - 3);

        var varToAdd = triDig[0] + triDig[1] + triDig[2];
        finlOutPut.push(varToAdd);
        i--;
        numString = numString.substring(0, numString.length - 3);
    }
    finlOutPut.push(numString);
    finlOutPut.reverse();

    //conver each grup of three digits to english word
    //if all digits are zero the triConvert
    //function return the string "dontAddBigSufix"
    for (j = 0; j < finlOutPut.length; j++) {
        finlOutPut[j] = triConvert(parseInt(finlOutPut[j]));
    }

    var bigScalCntr = 0; //this int mark the million billion trillion... Arry

    for (b = finlOutPut.length - 1; b >= 0; b--) {
        if (finlOutPut[b] != "dontAddBigSufix") {
            finlOutPut[b] = finlOutPut[b] + bigNumArry[bigScalCntr] + ' , ';
            bigScalCntr++;
        }
        else {
            //replace the string at finlOP[b] from "dontAddBigSufix" to empty String.
            finlOutPut[b] = ' ';
            bigScalCntr++; //advance the counter  
        }
    }

        //convert The output Arry to , more printable string 
        for(n = 0; n<finlOutPut.length; n++){
            output +=finlOutPut[n];
        }

    document.getElementById('container').innerHTML = output;//print the output
}

//simple function to convert from numbers to words from 1 to 999
function triConvert(num){
    var ones = new Array('', ' one', ' two', ' three', ' four', ' five', ' six', ' seven', ' eight', ' nine', ' ten', ' eleven', ' twelve', ' thirteen', ' fourteen', ' fifteen', ' sixteen', ' seventeen', ' eighteen', ' nineteen');
    var tens = new Array('', '', ' twenty', ' thirty', ' forty', ' fifty', ' sixty', ' seventy', ' eighty', ' ninety');
    var hundred = ' hundred';
    var output = '';
    var numString = num.toString();

    if (num == 0) {
        return 'dontAddBigSufix';
    }
    //the case of 10, 11, 12 ,13, .... 19 
    if (num < 20) {
        output = ones[num];
        return output;
    }

    //100 and more
    if (numString.length == 3) {
        output = ones[parseInt(numString.charAt(0))] + hundred;
        output += tens[parseInt(numString.charAt(1))];
        output += ones[parseInt(numString.charAt(2))];
        return output;
    }

    output += tens[parseInt(numString.charAt(0))];
    output += ones[parseInt(numString.charAt(1))];

    return output;
}   
<input type="text"
    id="number"
    size="70"
    onkeyup="update();"
    /*this code prevent non numeric letters*/ 
    onkeydown="return (event.ctrlKey || event.altKey 
                    || (47<event.keyCode && event.keyCode<58 && event.shiftKey==false) 
                    || (95<event.keyCode && event.keyCode<106)
                    || (event.keyCode==8) || (event.keyCode==9) 
                    || (event.keyCode>34 && event.keyCode<40) 
                    || (event.keyCode==46) )"/>
                    <br/>
<div id="container">Here The Numbers Printed</div>

当存在前导零数字时,JavaScript 会将 3 个数字组成的组解析为八进制数。当三位数字全为零时,无论基数是八进制还是十进制,结果都是相同的。

但是当你给 JavaScript '009'(或'008')时,这是一个无效的八进制数,所以你会得到零。

如果您浏览了从 190,000,001 到 190,000,010 的整组数字,您会看到 JavaScript 跳过“...,008”和“...,009”,但为“...,010”发出“8”。这就是“尤里卡!”片刻。

Change:

for (j = 0; j < finlOutPut.length; j++) {
    finlOutPut[j] = triConvert(parseInt(finlOutPut[j]));
}

to

for (j = 0; j < finlOutPut.length; j++) {
    finlOutPut[j] = triConvert(parseInt(finlOutPut[j],10));
}

代码还继续在每个非零组之后添加逗号,因此我使用它并找到了添加逗号的正确位置。

Old:

for (b = finlOutPut.length - 1; b >= 0; b--) {
    if (finlOutPut[b] != "dontAddBigSufix") {
        finlOutPut[b] = finlOutPut[b] + bigNumArry[bigScalCntr] + ' , ';
        bigScalCntr++;
    }
    else {
        //replace the string at finlOP[b] from "dontAddBigSufix" to empty String.
        finlOutPut[b] = ' ';
        bigScalCntr++; //advance the counter  
    }
}

    //convert The output Arry to , more printable string 
    for(n = 0; n<finlOutPut.length; n++){
        output +=finlOutPut[n];
    }

New:

for (b = finlOutPut.length - 1; b >= 0; b--) {
    if (finlOutPut[b] != "dontAddBigSufix") {
        finlOutPut[b] = finlOutPut[b] + bigNumArry[bigScalCntr]; // <<<
        bigScalCntr++;
    }
    else {
        //replace the string at finlOP[b] from "dontAddBigSufix" to empty String.
        finlOutPut[b] = ' ';
        bigScalCntr++; //advance the counter  
    }
}

    //convert The output Arry to , more printable string 
    var nonzero = false; // <<<
    for(n = 0; n<finlOutPut.length; n++){
        if (finlOutPut[n] != ' ') { // <<<
            if (nonzero) output += ' , '; // <<<
            nonzero = true; // <<<
        } // <<<
        output +=finlOutPut[n];
    }
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

JavaScript 数字到单词 的相关文章

随机推荐

  • 将分支合并到目录 GIT

    我有一个名为Project 然后我有一个名为payment其中包含应用程序的所有项目文件 我想合并分支payment进入我的主分支 但在文件夹 目录内 换句话说 项目分支 gt 支付申请 文件夹 gt 支付分支文件 第一次 git chec
  • C++ 中嵌套类型/类的前向声明

    我最近陷入了这样的情况 class A public typedef struct class B C D someField class C public typedef struct class D A B someField 通常你可
  • 使用 anaconda python3 安装 opencv 3.1?

    如何使用 anaconda python3 安装 opencv opencv 获取了我的 python3 可执行文件 Python 2 Interpreter usr bin python2 7 ver 2 7 12 Libraries u
  • Vue Router 推送错误:避免了到当前位置的冗余导航

    有没有办法避免错误 避免冗余导航到当前位置 我需要进行分页 方法如下 handlePageChange page number void const query this route query page page toString thi
  • ActiveJob GlobalID 和内存中 ActiveRecord 对象

    我正在使用排队系统 Sidekiq 并且希望迁移到 ActiveJob 以获得性能优势 因为不必每次将 ActiveRecord 对象传递给工作人员时都查询数据库 我想询问并确认 因为我不是 100 确定 但我的理解是 当 ActiveJo
  • 使用依赖属性和样式触发器时,“...不是 DependencyProperty”

    在我的用户控件中 public ODIF DeviceChannel Channel get return ODIF DeviceChannel GetValue ChannelDP set SetValue ChannelDP value
  • TableDnD onDrop 事件未触发

    我确信这是非常简单的事情 通常都是如此 sort table tableDnD onDragClass dnd drag onDragStart function table row console log start drag onDro
  • 如何从标准输入中读取一行,并将其余行传递给子进程?

    If you readline from sys stdin 将其余部分传递给子进程似乎不起作用 import subprocess import sys header sys stdin buffer readline print hea
  • 如何在servlet中获取客户端的远程地址?

    有什么办法可以获取到服务器的客户端的原始IP地址吗 我可以用request getRemoteAddr 但我似乎总是获得代理或网络服务器的IP 我想知道客户端用于连接到我的 IP 地址 无论如何 我能得到它吗 尝试这个 public sta
  • Visual Studio 2012 是否利用所有可用的 CPU 内核?

    我计划在 Visual Studio 2012 和 Windows 7 64 位下构建一台新的非常快的开发计算机 我正在购买所有快速组件 例如 SSD 和 16G RAM 我想知道是否视觉工作室2012旨在利用所有可用的 CPU 内核 我正
  • 每次出现错误时使用 prometheus 创建警报

    我是普罗米修斯和警报系统的新手 我开发了一个微服务并添加了指标代码 以便在出现错误时获取增量总数 现在我正在尝试创建一个警报 以便每当错误增加时 它应该标记出来并发送邮件 但我无法针对这种情况形成正确的查询 我使用了诸如 error tot
  • CoreMotion 陀螺仪苹果手表

    我正在尝试访问苹果手表的陀螺仪 据我所知 它可以在 watchos 3 中使用 不幸的是我无法让它工作 它不断返回 陀螺仪不可用 因此 MotionManager isGyroAvailable 始终为 false 这是我的代码 任何帮助
  • Kotlin 本地函数必须在使用前声明

    在这个简单的代码示例中 fun testLocalFunctions aLocalFun compiler error unresolved reference at aLocalFun fun aLocalFun aLocalFun no
  • 如何保持领域数据与输入的顺序相同

    我有一个应用程序 需要将数据按照输入的顺序保存 数据被输入到 List 属性中 一切都很顺利 直到我必须删除一个项目 当删除发生时 列表中的最后一项将取代被删除的一项 UITableView 显示正确的项目数 但与领域列表不同步 一个例子是
  • R中的顺序混淆矩阵

    我根据 3 个类别的观察结果及其预测创建了一个混淆矩阵 classes c Underweight Normal Overweight 当我计算混淆矩阵时 它会按字母顺序组织表中的类 这是我的代码 Confusion matrix Obse
  • 为什么此解释中没有使用密钥?

    我期望这个查询使用密钥 mysql gt DESCRIBE TABLE Foo Field Type Null Key Default Extra id bigint 20 NO PRI NULL auto increment name v
  • 如何正确编写 Swift UI Toggle 的 UI 测试

    有谁知道如何正确编写 Toggle 的 UI 测试 即使在一个全新的项目中 整个 UI 中只有一个切换而没有其他内容 我仍然会收到此类错误 Failed to get matching snapshot Multiple matching
  • OpenCV detectorMultiScale() 参数的推荐值

    推荐的参数是什么CascadeClassifier detectMultiScale http docs opencv org modules objdetect doc cascade classification html cascad
  • 如何在 Node.js 中将 JPG 图像转换为 WEBP 格式?

    我正在尝试使用react Js上传图像并使用multer中间件将该图像保存在node Js中 这是完美的 但现在我想使用 webp converter 将该图像转换为 WEBP 格式 反之亦然 但我收到此错误 Error Command f
  • JavaScript 数字到单词

    例如 我正在尝试将数字转换为英语单词1234会成为 一千二百三十四 我的策略是这样的 将数字分成三位并将它们放入数组 finlOutPut 从右到左 转换每个组 每个单元格中finlOutPut数组 的三个数字到一个单词 这就是triCon