个性化阅读
专注于IT技术分析

如何在JavaScript中将数字转换为单词(数字拼写)

点击下载

本文概述

编程的目标是多目标优化, 我们编写代码来自动完成需要一些时间才能手动完成的事情。对于许多项目, 你需要将数字转换为其单词表示形式, 以防止用户将整个数字写成单词(例如, 带有单词的数字123456789将为一亿二千三百万, 四十五万六千七, 七一百八十九)。是的, 这是一个非常长的数字, 我知道你甚至都没有读完整的数字, 所以, 你的用户为什么要自己写呢?通过自动化使你的用户轻松完成此任务。

在本文中, 你将学习使用库或使用单个函数将数字转换为其单词表示形式。

A.使用第三方库

要将数字转换为使用Javascript的单词, 我们将使用numberToWords包。此模块包含一些util方法, 用于将数字转换为单词, 序数单词和序数数字。

你可以在执行npm的情况下安装此模块(因为该模块已在npm上注册, 因此它也可以与Node.js完美配合):

npm install number-to-words

或者, 如果你使用凉亭:

bower install number-to-words

如果你不使用任何Java包管理器, 只需在此处下载存储库的缩小文件即可。然后, 在浏览器中, numberToWords变量将在文档中全局访问, 然后使用脚本标记在文档中包含numberToWords.min.js文件:

<script type="text/javascript" src="/path/to/numberToWords.min.js"></script>

如果你需要有关此项目的更多信息, 请在此处访问Github中的官方资源库。

注意

该库仅转换整数, 任何浮点值将自动解析为整数。

用法

该库提供3种方法, 使你可以将整数(或字符串类型的数字)转换为单词。请记住, 如果你使用的是requireJS, 则需要使用该模块:

// If you're using Node.js or browserify (requireJS)
// require the module using:
var numberToWords = require('number-to-words');
numberToWords.toWords(13); // => "thirteen"


// If you're using the script in the browser
// then the global "numberToWords" variable will be accesible in the window
numberToWords.toOrdinal(1);
numberToWords.toWordsOrdinal(1);
numberToWords.toWords(1);

1.将数字转换为其缩写序数

你可以使用此库轻松地将数字转换为普通数, 序数定义了一系列内容的位置, 例如第一, 第二或第三。序数用作形容词, 名词和代词。

要将数字转换为缩写序数, 请使用.toOrdinal方法:

// 1st
numberToWords.toOrdinal(1);
// 2nd
numberToWords.toOrdinal(2);
// 3rd
numberToWords.toOrdinal(3);

// 1500th
numberToWords.toOrdinal(1500);
// 1234567890th
numberToWords.toOrdinal(1234567890);

该方法返回一个字符串, 该字符串以Providen整数(或字符串)的缩写序数值为第一个参数。

2.用数字将数字转换为其序数

除了使用缩写外, numberToWords还允许你使用.toWordsOrdinal方法将数字转换为单词中的序数:

// first
numberToWords.toWordsOrdinal(1);
// second
numberToWords.toWordsOrdinal(2);
// third
numberToWords.toWordsOrdinal(3);

// one thousand, five hundredth
numberToWords.toWordsOrdinal(1500);
// one billion, two hundred thirty-four million, five hundred sixty-seven thousand, eight hundred ninetieth
numberToWords.toWordsOrdinal(1234567890);

非常棒且简单, 不是吗?

3.将数字转换为单词

你可以使用.toWords方法轻松地将数字转换为其单词表示形式:

// one
numberToWords.toWords(1);
// two
numberToWords.toWords(2);
// three
numberToWords.toWords(3);

// one thousand, five hundred
numberToWords.toWords(1500);
// one billion, two hundred thirty-four million, five hundred sixty-seven thousand, eight hundred ninety
numberToWords.toWords(1234567890);

重要的提示

该库最多支持999999999999999(15位数字)的转换。

使用数量更大的库将不可避免地导致异常Uncaught RangeError:超出了最大调用堆栈大小, 可以轻松防止使用try / catch语句。

自我实施

如果你不想使用库来实现目标, 而只想使用简单的代码段将数字转换为单词, 则可以使用以下简单函数:

/**
 * Convert an integer to its words representation
 * 
 * @author McShaman (http://stackoverflow.com/users/788657/mcshaman)
 * @source http://stackoverflow.com/questions/14766951/convert-digits-into-words-with-javascript
 */
function numberToEnglish(n, custom_join_character) {

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

    var and = custom_join_character || 'and';

    /* 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 && chunksLen) {
                    words.push(and);
                }

            }

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

        }

    }

    return words.reverse().join(' ');

}

你可以轻松使用:

// one hundred and twenty three million four hundred and fifty six thousand seven hundred and eighty nine
numberToEnglish(123456789);

// Use a custom separator (like , instead of "and")
// one hundred , twenty three million four hundred , fifty six thousand seven hundred , eighty nine
numberToEnglish(123456789, ", ");

以与库相同的方式, 最多只能输入15位数字。但是, 在这种情况下, 此函数不会引发异常, 但是将以字生成的值将不正确。此外, 此实现不支持转换为序数。

编码愉快!

赞(0)
未经允许不得转载:srcmini » 如何在JavaScript中将数字转换为单词(数字拼写)

评论 抢沙发

评论前必须登录!