Convert a number to its string representation

前端 未结 4 1710
野性不改
野性不改 2021-01-13 21:53

I\'m developing a simple web application where in I need to display number a to my users in string format.

Example:

12 - One Two or Twelve
-20 - min         


        
4条回答
  •  醉梦人生
    2021-01-13 22:22

    Building on the work that @SRC did in a previous answer, I wrote a function to convert any raw unsigned integer into English, mainly out of curiosity.

    You can find the code here: a GitHub Gist by StampyCode

    This code is only limited by PHP's Integer limit (64-bit):

    9223372036854775807
    

    Which is processed by this code to output:

    nine quintillion, two hundred and twenty three quadrillion, three hundred and seventy two trillion, thirty six billion, eight hundred and fifty four million, seven hundred and seventy five thousand, eight hundred and seven

    Code embed:

     'hundred',
        3  => 'thousand',
        6  => 'million',
        9  => 'billion',
        12 => 'trillion',
        15 => 'quadrillion',
        18 => 'quintillion',
        21 => 'sextillion',
        24 => 'septillion', // php can't count this high
        27 => 'octillion',
    ];
    $fnBase = function ($n, $x) use (&$fn, $_mult) {
        return $fn($n / (10 ** $x)) . ' ' . $_mult[$x];
    };
    $fnOne = function ($n, $x) use (&$fn, &$fnBase) {
        $y = ($n % (10 ** $x)) % (10 ** $x);
        $s = $fn($y);
        $sep = ($x === 2 && $s ? " and " : ($y < 100 ? ($y ? " and " : '') : ', '));
        return $fnBase($n, $x) . $sep . $s;
    };
    $fnHundred = function ($n, $x) use (&$fn, &$fnBase) {
        $y = $n % (10 ** $x);
        $sep = ($y < 100 ? ($y ? ' and ' : '') : ', ');
        return ', ' . $fnBase($n, $x) . $sep . $fn($y);
    };
    $fn = function ($n) use (&$fn, $_1to19, $_teen, $number, &$fnOne, &$fnHundred) {
        switch ($n) {
            case 0:
                return ($number > 1 ? '' : 'zero');
            case $n < 20:
                return $_1to19[$n - 1];
            case $n < 100:
                return $_teen[($n / 10) - 2] . ' ' . $fn($n % 10);
            case $n < (10 ** 3):
                return $fnOne($n, 2);
        };
        for ($i = 4; $i < 27; ++$i) {
            if ($n < (10 ** $i)) {
                break;
            }
        }
        return ($i % 3) ? $fnHundred($n, $i - ($i % 3)) : $fnOne($n, $i - 3);
    };
    $number = $fn((int)$number);
    $number = str_replace(', , ', ', ', $number);
    $number = str_replace(',  ', ', ', $number);
    $number = str_replace('  ', ' ', $number);
    $number = ltrim($number, ', ');
    
    return $number;
    

提交回复
热议问题