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

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

本文概述

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

要求

为了将数字转换为单词, 我们将使用PEAR的numbers_words包。此类可以将整数更改为简单的单词。当你需要拼写货币值(例如, 在发票上。该软件包提供对20多种语言的支持, 包括英语, 德语, 西班牙语, 瑞典语, 土耳其语, 俄语和其他语言。根据最后的测试, 它最多可以转换14位数字的值。

安装

要将项目中的numbers_words作为依赖项添加, 请在终端中执行以下命令:

composer require pear/numbers_words

或修改项目的composer.json文件, 手动添加依赖项, 然后执行composer install:

{
    "require": {
        "pear/numbers_words": "^0.18.1"
    }
}

安装后, 你将可以通过导入Numbers_Words类在项目中使用该软件包。

用法

Numbers_words类提供了toWords的静态方法。此方法期望将要转换为单词的整数作为第一个参数, 并将期望的语言的语言标识符作为第二个参数, 例如英语:

<?php

namespace AppBundle\Controller;

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Response;

// Import the class
use Numbers_Words;

class DefaultController extends Controller
{
    /**
     * @Route("/", name="homepage")
     */
    public function indexAction()
    {
        $numberToConvert = 99999999999999;
        $localeEnglish = "en_US"; // Or en_GB
        
        $wordsFromValue = Numbers_Words::toWords($numberToConvert, $localeEnglish);

        return new Response($wordsFromValue);
    }
}

前任控制者的响应将是990万亿999 990亿990 9.9亿。

其他语言

如前所述, 该软件包提供了对20多种语言的支持。你只需在静态方法中为你的语言代码提供第二个参数即可(有关更多代码, 请访问存储库):

<?php

namespace AppBundle\Controller;

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Response;

// Import the class
use Numbers_Words;

class DefaultController extends Controller
{
    /**
     * @Route("/", name="homepage")
     */
    public function indexAction()
    {
        $numberToConvert = 123456789;

        $supportedLanguages = array(
            array("languageName" => "Bulgarian", "languageCode" => "bg"), array("languageName" => "German", "languageCode" => "de"), array("languageName" => "Danish", "languageCode" => "dk"), array("languageName" => "Donald Knuth number naming system", "languageCode" => "en_100"), // notation of numbers, where one billion is 1000000 times one million.
            // 1000 times million is just 'thousand million' here. The word billiard here is not used
            // because English people do not use it often, and even could not know it.
            array("languageName" => "British English", "languageCode" => "en_GB"), array("languageName" => "American English", "languageCode" => "en_US"), array("languageName" => "Spanish (Castellano)", "languageCode" => "es"), array("languageName" => "Spanish Argentinian", "languageCode" => "es_AR"), array("languageName" => "French ", "languageCode" => "fr"), array("languageName" => "French (Belgium)", "languageCode" => "fr_BE"), array("languageName" => "Hebrew", "languageCode" => "he"), array("languageName" => "Indonesia", "languageCode" => "id"), array("languageName" => "Italian", "languageCode" => "it_IT"), array("languageName" => "Lithuanian ", "languageCode" => "lt"), array("languageName" => "Dutch  ", "languageCode" => "nl"), array("languageName" => "Polish", "languageCode" => "pl"), array("languageName" => "Brazilian ", "languageCode" => "pt_BR"), array("languageName" => "Romanian ", "languageCode" => "ro_RO"), array("languageName" => "Russian ", "languageCode" => "ru"), array("languageName" => "Turkish  ", "languageCode" => "tr_TR")
        );

        $responseString = "";

        foreach($supportedLanguages as $language){
            $convertedNumber = Numbers_Words::toWords($numberToConvert, $language["languageCode"]);

            $responseString .= $language["languageName"] . " : ". $convertedNumber . "<br>";
        }

        $response = new Response($responseString);
        $response->setCharset('UTF-8');
        $response->headers->remove('Cache-Control');
        $response->headers->set('Content-Type', 'text/html');

        return $response;
    }
}

响应将是:

Bulgarian : сто двадесет и три милиона четиристотин петдесет и шест хиляди седемстотин осемдесет и деветGerman : einhundertdreiundzwanzig Millionen vierhundertsechsundfünfzigtausendsiebenhundertneunundachtzigDanish : et hundrede tre og tyve millioner fire hundrede seks og halvtreds tusinde syv hundrede ni og firsDonald Knuth number naming system : one myllion twenty-three hundred myriad forty-five myriad sixty-seven hundred eighty-nineBritish English : one hundred twenty-three million four hundred fifty-six thousand seven hundred eighty-nineAmerican English : one hundred twenty-three million four hundred fifty-six thousand seven hundred eighty-nineSpanish (Castellano) : ciento veintitres millones cuatrocientos cincuenta y seis mil setecientos ochenta y nueveSpanish Argentinian : ciento veintitres millones cuatrocientos cincuenta y seis mil setecientos ochenta y nueveFrench : cent vingt-trois millions quatre cent cinquante-six mille sept cent quatre-vingt-neufFrench (Belgium) : cent vingt-trois millions quatre cent cinquante-six mille sept cent quatre-vingt-neufHebrew : מאה עשרים ושלושה מיליון ארבע-מאות חמישים ושישה אלפים שבע-מאות שמונים ותשעהIndonesia : seratus dua puluh tiga juta empat ratus lima puluh enam ribu tujuh ratus delapan puluh sembilanItalian : centoventitremiloniquattrocentocinquantaseimilasettecentoottantanoveLithuanian : šimtas dvidešimt trys milijonai keturi šimtai penkiasdešimt šeši tūkstančiai septyni šimtai aštuoniasdešimt devyniDutch : eenhonderddrieentwintig-Miljoen-vierhonderdzesenvijftigDuizendzevenhonderdnegenenachttigPolish : sto dwadzieścia trzy miliony czterysta pięćdziesiąt sześć tysięcy siedemset osiemdziesiąt dziewięćBrazilian : cento e vinte e três milhões quatrocentos e cinqüenta e seis mil setecentos e oitenta e noveRomanian : una sută douăzeci și trei de milioane patru sute cincizeci și șase de mii șapte sute optzeci și nouăRussian : сто двадцать три миллиона четыреста пятьдесят шесть тысяч семьсот восемьдесят девятьTurkish : bir yüz yirmi üç milyon dört yüz elli altı bin yedi yüz seksen dokuz

编码愉快!

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

评论 抢沙发

评论前必须登录!