[SOURCE] Convertir numero a texto con PHP (Class)

Iniciado por kid_goth, Septiembre 09, 2014, 04:15:46 PM

Tema anterior - Siguiente tema

0 Miembros y 1 Visitante están viendo este tema.

Hola,

Necesitaba convertir los valores que se ingresaban en formato numero a texto por ejemplo 1000 -> mil y pues estaba por empezar a hacer la clase y que se me da por buscar y encontré una clase en stackoverflow pero en ingles entonces pues la traduje y le cambié algunas cosas como que por ejemplo allá dicen one thousand y aca puel mil y ya (mas no un mil) o que en muchas partes de habla inglesa llaman a los miles de millones como billones etc... Ademas de que lo dejej como una clase ya que estaban en funciones sueltas... sin mas les comparto ambos códigos (de paso el link pastebin) y la fuente :D

Ingles: No tienes permitido ver los links. Registrarse o Entrar a mi cuenta

Código: php
<?php

/**
* English Number Converter - Collection of PHP functions to convert a number
*                            into English text.
*
* This exact code is licensed under CC-Wiki on Stackoverflow.
* http://creativecommons.org/licenses/by-sa/3.0/
*
* @link     http://stackoverflow.com/q/277569/367456
* @question Is there an easy way to convert a number to a word in PHP?
*
* This file incorporates work covered by the following copyright and
* permission notice:
*
*   Copyright 2007-2008 Brenton Fletcher. http://bloople.net/num2text
*   You can use this freely and modify it however you want.
*
* Class for POO by kid_goth
*/
class Num2TextEng {

    public function convertNumber($number) {
        $output = "";

        if (preg_match('/\./', $number)) {
            list($integer, $fraction) = explode(".", (string) $number);
        } else {
            $integer = (string) $number;
            $fraction = NULL;
        }

        if ($integer{0} == "-") {
            $output = "negative ";
            $integer = ltrim($integer, "-");
        } else if ($integer{0} == "+") {
            $output = "positive ";
            $integer = ltrim($integer, "+");
        }

        if ($integer{0} == "0") {
            $output .= "zero";
        } else {
            $integer = str_pad($integer, 36, "0", STR_PAD_LEFT);
            $group = rtrim(chunk_split($integer, 3, " "), " ");
            $groups = explode(" ", $group);

            $groups2 = array();
            foreach ($groups as $g) {
                $groups2[] = $this->convertThreeDigit($g{0}, $g{1}, $g{2});
            }

            for ($z = 0; $z < count($groups2); $z++) {
                if ($groups2[$z] != "") {
                    $output .= $groups2[$z] . $this->convertGroup(11 - $z) . (
                            $z < 11 && !array_search('', array_slice($groups2, $z + 1, -1)) && $groups2[11] != '' && $groups[11]{0} == '0' ? " and " : ", "
                            );
                }
            }

            $output = rtrim($output, ", ");
        }

        if ($fraction > 0) {
            $output .= " point";
            for ($i = 0; $i < strlen($fraction); $i++) {
                $output .= " " . $this->convertDigit($fraction{$i});
            }
        }

        return $output;
    }

    private function convertGroup($index) {
        switch ($index) {
            case 11:
                return " decillion";
            case 10:
                return " nonillion";
            case 9:
                return " octillion";
            case 8:
                return " septillion";
            case 7:
                return " sextillion";
            case 6:
                return " quintrillion";
            case 5:
                return " quadrillion";
            case 4:
                return " trillion";
            case 3:
                return " billion";
            case 2:
                return " million";
            case 1:
                return " thousand";
            case 0:
                return "";
        }
    }

    private function convertThreeDigit($digit1, $digit2, $digit3) {
        $buffer = "";

        if ($digit1 == "0" && $digit2 == "0" && $digit3 == "0") {
            return "";
        }

        if ($digit1 != "0") {
            $buffer .= $this->convertDigit($digit1) . " hundred";
            if ($digit2 != "0" || $digit3 != "0") {
                $buffer .= " and ";
            }
        }

        if ($digit2 != "0") {
            $buffer .= $this->convertTwoDigit($digit2, $digit3);
        } else if ($digit3 != "0") {
            $buffer .= $this->convertDigit($digit3);
        }

        return $buffer;
    }

    private function convertTwoDigit($digit1, $digit2) {
        if ($digit2 == "0") {
            switch ($digit1) {
                case "1":
                    return "ten";
                case "2":
                    return "twenty";
                case "3":
                    return "thirty";
                case "4":
                    return "forty";
                case "5":
                    return "fifty";
                case "6":
                    return "sixty";
                case "7":
                    return "seventy";
                case "8":
                    return "eighty";
                case "9":
                    return "ninety";
            }
        } else if ($digit1 == "1") {
            switch ($digit2) {
                case "1":
                    return "eleven";
                case "2":
                    return "twelve";
                case "3":
                    return "thirteen";
                case "4":
                    return "fourteen";
                case "5":
                    return "fifteen";
                case "6":
                    return "sixteen";
                case "7":
                    return "seventeen";
                case "8":
                    return "eighteen";
                case "9":
                    return "nineteen";
            }
        } else {
            $temp = $this->convertDigit($digit2);
            switch ($digit1) {
                case "2":
                    return "twenty-$temp";
                case "3":
                    return "thirty-$temp";
                case "4":
                    return "forty-$temp";
                case "5":
                    return "fifty-$temp";
                case "6":
                    return "sixty-$temp";
                case "7":
                    return "seventy-$temp";
                case "8":
                    return "eighty-$temp";
                case "9":
                    return "ninety-$temp";
            }
        }
    }

    private function convertDigit($digit) {
        switch ($digit) {
            case "0":
                return "zero";
            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";
        }
    }

}

/**
* Example of use:
*
* http://localhost/Num2TextEng.php?n=1000
* */
$objNum2TextEng = new Num2TextEng();
$_G = filter_input(INPUT_GET, 'n');
echo $objNum2TextEng->convertNumber($_G);

// Output: one thousand



Español: No tienes permitido ver los links. Registrarse o Entrar a mi cuenta

Código: php
<?php

/**
* Tomado de:
*  Copyright 2007-2008 Brenton Fletcher. http://bloople.net/num2text
*  @link     http://stackoverflow.com/q/277569/367456
*  @question Is there an easy way to convert a number to a word in PHP?
*
* Bajo la licencia de CC-Wiki on Stackoverflow.
* http://creativecommons.org/licenses/by-sa/3.0/
*
*
* Modificado por kid_goth para uso en regiones de habla española
* En donde se 1.000.000.000 es igual a Mil millones y no a un
* billon como se usa en las regiones de habla inglesa. Ademas de agregar
* POO a la programacion.
*
*  @contact Twitter: @_kid_goth
*/
class Num2Text {

    public function convertNumber($number) {
        $output = "";

        if (preg_match('/\./', $number)) {
            list($integer, $fraction) = explode(".", (string) $number);
        } else {
            $integer = (string) $number;
            $fraction = NULL;
        }

        if ($integer{0} == "-") {
            $output = "negativo ";
            $integer = ltrim($integer, "-");
        } else if ($integer{0} == "+") {
            $output = "positivo ";
            $integer = ltrim($integer, "+");
        }

        if ($integer{0} == "0") {
            $output .= "cero";
        } else {
            $integer = str_pad($integer, 36, "0", STR_PAD_LEFT);
            $group = rtrim(chunk_split($integer, 3, " "), " ");
            $groups = explode(" ", $group);

            $groups2 = array();
            foreach ($groups as $g) {
                $groups2[] = $this->convertThreeDigit($g{0}, $g{1}, $g{2});
            }

            for ($z = 0; $z < count($groups2); $z++) {
                if ($groups2[$z] != "") {
                    $rtnGroup = $this->convertGroup(11 - $z, $groups2[$z]);
                    $output = preg_replace("/" . $rtnGroup . " /", "", $output);
                    $output .= $groups2[$z] . $rtnGroup . (
                            $z < 11 && !array_search('', array_slice($groups2, $z + 1, -1)) && $groups2[11] != '' && $groups[11]{0} == '0' ? " " : " "
//$z < 11 && !array_search('', array_slice($groups2, $z + 1, -1)) && $groups2[11] != '' && $groups[11]{0} == '0' ? " and " : ", "
                            );
                }
            }

            $output = rtrim($output, ", ");
        }

        if ($fraction > 0) {
            $output .= " punto";
            for ($i = 0; $i < strlen($fraction); $i++) {
                $output .= " " . $this->convertDigit($fraction{$i});
            }
        }

        return preg_replace('/un mil\b/', 'mil', $output);
    }

    private function convertGroup($index, $valor = '') {
        switch ($index) {
            case 12:
                if ($valor != 'un') {
                    return " sextillones";
                } else {
                    return " sextillon";
                }
            case 11:
                return " mil quintillones";
            case 10:
                if ($valor != 'un') {
                    return " quintillones";
                } else {
                    return " quintillon";
                }
            case 9:
                return " mil cuadrillones";
            case 8:
                if ($valor != 'un') {
                    return " cuadrillones";
                } else {
                    return " cuadrillon";
                }
            case 7:
                return " mil trillones";
            case 6:
                if ($valor != 'un') {
                    return " trillones";
                } else {
                    return " trillon";
                }
            case 5:
                return " mil billones";
            case 4:
                if ($valor != 'un') {
                    return " billones";
                } else {
                    return " billon";
                }
            case 3:
                return " mil millones";
            case 2:
                if ($valor != 'un') {
                    return " millones";
                } else {
                    return " millon";
                }
            case 1:
                return " mil";
            case 0:
                return "";
        }
    }

    private function convertThreeDigit($digit1, $digit2, $digit3) {
        $buffer = "";

        if ($digit1 == "0" && $digit2 == "0" && $digit3 == "0") {
            return "";
        }

        if ($digit1 != "0") {
            $buffer .= $this->convertCientos($digit1);
            if ($digit2 != "0" || $digit3 != "0") {
                $buffer .= " ";
            }
        }

        if ($digit2 != "0") {
            $buffer .= $this->convertTwoDigit($digit2, $digit3);
        } else if ($digit3 != "0") {
            $buffer .= $this->convertDigit($digit3);
        }

        return $buffer;
    }

    private function convertTwoDigit($digit1, $digit2) {
        if ($digit2 == "0") {
            switch ($digit1) {
                case "1":
                    return "diez";
                case "2":
                    return "veinte";
                case "3":
                    return "treinta";
                case "4":
                    return "cuarenta";
                case "5":
                    return "cincuenta";
                case "6":
                    return "sesenta";
                case "7":
                    return "setenta";
                case "8":
                    return "ochenta";
                case "9":
                    return "noventa";
            }
        } else if ($digit1 == "1") {
            switch ($digit2) {
                case "1":
                    return "once";
                case "2":
                    return "doce";
                case "3":
                    return "trece";
                case "4":
                    return "catorce";
                case "5":
                    return "quince";
                case "6":
                    return "diez y seis";
                case "7":
                    return "diez y siete";
                case "8":
                    return "diez y ocho";
                case "9":
                    return "diez y nueve";
            }
        } else {
            $temp = $this->convertDigit($digit2);
            switch ($digit1) {
                case "2":
                    return "veinti$temp";
                case "3":
                    return "treinta y $temp";
                case "4":
                    return "cuarenta y $temp";
                case "5":
                    return "cincuenta y $temp";
                case "6":
                    return "sesenta y $temp";
                case "7":
                    return "setenta y $temp";
                case "8":
                    return "ochenta y $temp";
                case "9":
                    return "noventa y $temp";
            }
        }
    }

    private function convertCientos($digit) {
        switch ($digit) {
            case "0":
                return "cero";
            case "1":
                return "ciento";
            case "2":
                return "docientos";
            case "3":
                return "trecientos";
            case "4":
                return "cuatrocientos";
            case "5":
                return "quinientos";
            case "6":
                return "seicientos";
            case "7":
                return "setecientos";
            case "8":
                return "ochocientos";
            case "9":
                return "novecientos";
        }
    }

    private function convertDigit($digit) {
        switch ($digit) {
            case "0":
                return "cero";
            case "1":
                return "un";
            case "2":
                return "dos";
            case "3":
                return "tres";
            case "4":
                return "cuatro";
            case "5":
                return "cinco";
            case "6":
                return "seis";
            case "7":
                return "siete";
            case "8":
                return "ocho";
            case "9":
                return "nueve";
        }
    }

}

/**
* Ejemplo de Uso:
*
* http://localhost/Num2Text.php?n=1000
**/

$objNum2Text = new Num2Text();
$_G = filter_input(INPUT_GET, 'n');
echo $objNum2Text->convertNumber($_G);

// Salida: mil


Fuente: No tienes permitido ver los links. Registrarse o Entrar a mi cuenta

No tienes permitido ver los links. Registrarse o Entrar a mi cuenta

Acepta con humildad y aprecio que en la vida la muerte es inevitable y amarás ésta, adorando la muerte