Perl en Español

  1. Home
  2. Tutoriales
  3. Foro
  4. Artículos
  5. Donativos
  6. Publicidad
 
Índice general » Otros Temas » JavaScript » Convertir números a letras  RESUELTO Responder al tema
Nuevo tema


Página 1 de 1  [ 5 mensajes ] 
 
Nota Dom Nov 30, 2008 11:33 am

Perlero Nuevo
Registrado: Vie Sep 12, 2008 9:36 am
Mensajes: 16
Convertir números a letras
Estimados amigos:
Me devano los sesos y no doy con el error. Este script convierte números a letras, me parece muy útil. El problema es que cuando el número decimal es igual o mayor que 0.50 devuelve el entero aumentado en uno.
Por ejemplo: 23.40 devuelve veintitrés y 40 (bien)
pero en 23.50 devuelve veinticuatro y 50 (error)

Les envió el script a ver si solucionan el error, les agradezco cualquier ayuda.

Syntax: [ Download ] [ Hide ]
Using javascript Syntax Highlighting
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>

<script language="javascript">
 
// Función modulo, regresa el residuo de una división
function mod(dividendo , divisor)
{
  resDiv = dividendo / divisor ;  
  parteEnt = Math.floor(resDiv);            // Obtiene la parte Entera de resDiv
  parteFrac = resDiv - parteEnt ;      // Obtiene la parte Fraccionaria de la división
  modulo = Math.round(parteFrac * divisor);  // Regresa la parte fraccionaria * la división (modulo)
  return modulo;
} // Fin de función mod

// Función ObtenerParteEntDiv, regresa la parte entera de una división
function ObtenerParteEntDiv(dividendo , divisor)
{
  resDiv = dividendo / divisor ;  
  parteEntDiv = Math.floor(resDiv);
  return parteEntDiv;
} // Fin de función ObtenerParteEntDiv

// function fraction_part, regresa la parte Fraccionaria de una cantidad
function fraction_part(dividendo , divisor)
{
  resDiv = dividendo / divisor ;  
  f_part = Math.floor(resDiv);
  return f_part;
} // Fin de función fraction_part


// function string_literal conversion is the core of this program
// converts numbers to spanish strings, handling the general special
// cases in spanish language.
function string_literal_conversion(number)
{  
   // first, divide your number in hundreds, tens and units, cascadig
   // trough subsequent divisions, using the modulus of each division
   // for the next.

   centenas = ObtenerParteEntDiv(number, 100);
   
   number = mod(number, 100);

   decenas = ObtenerParteEntDiv(number, 10);
   number = mod(number, 10);

   unidades = ObtenerParteEntDiv(number, 1);
   number = mod(number, 1);  
   string_hundreds="";
   string_tens="";
   string_units="";
   // cascade trough hundreds. This will convert the hundreds part to
   // their corresponding string in spanish.
   if(centenas == 1){
      string_hundreds = "ciento ";
   }
   
   
   if(centenas == 2){
      string_hundreds = "doscientos ";
   }
   
   if(centenas == 3){
      string_hundreds = "trescientos ";
   }
   
   if(centenas == 4){
      string_hundreds = "cuatrocientos ";
   }
   
   if(centenas == 5){
      string_hundreds = "quinientos ";
   }
   
   if(centenas == 6){
      string_hundreds = "seiscientos ";
   }
   
   if(centenas == 7){
      string_hundreds = "setecientos ";
   }
   
   if(centenas == 8){
      string_hundreds = "ochocientos ";
   }
   
   if(centenas == 9){
      string_hundreds = "novecientos ";
   }
   
 // end switch hundreds

   // casgade trough tens. This will convert the tens part to corresponding
   // strings in spanish. Note, however that the strings between 11 and 19
   // are all special cases. Also 21-29 is a special case in spanish.
   if(decenas == 1){
      //Special case, depends on units for each conversion
      if(unidades == 1){
         string_tens = "once";
      }
     
      if(unidades == 2){
         string_tens = "doce";
      }
     
      if(unidades == 3){
         string_tens = "trece";
      }
     
      if(unidades == 4){
         string_tens = "catorce";
      }
     
      if(unidades == 5){
         string_tens = "quince";
      }
     
      if(unidades == 6){
         string_tens = "dieciseis";
      }
     
      if(unidades == 7){
         string_tens = "diecisiete";
      }
     
      if(unidades == 8){
         string_tens = "dieciocho";
      }
     
      if(unidades == 9){
         string_tens = "diecinueve";
      }
   }
   //alert("STRING_TENS ="+string_tens);
   
   if(decenas == 2){
      string_tens = "veinti";

   }
   if(decenas == 3){
      string_tens = "treinta";
   }
   if(decenas == 4){
      string_tens = "cuarenta";
   }
   if(decenas == 5){
      string_tens = "cincuenta";
   }
   if(decenas == 6){
      string_tens = "sesenta";
   }
   if(decenas == 7){
      string_tens = "setenta";
   }
   if(decenas == 8){
      string_tens = "ochenta";
   }
   if(decenas == 9){
      string_tens = "noventa";
   }
   
    // Fin de swicth decenas


   // cascades trough units, This will convert the units part to corresponding
   // strings in spanish. Note however that a check is being made to see wether
   // the special cases 11-19 were used. In that case, the whole conversion of
   // individual units is ignored since it was already made in the tens cascade.

   if (decenas == 1)
   {
      string_units="";  // empties the units check, since it has alredy been handled on the tens switch
   }
   else
   {
      if(unidades == 1){
         string_units = "un";
      }
      if(unidades == 2){
         string_units = "dos";
      }
      if(unidades == 3){
         string_units = "tres";
      }
      if(unidades == 4){
         string_units = "cuatro";
      }
      if(unidades == 5){
         string_units = "cinco";
      }
      if(unidades == 6){
         string_units = "seis";
      }
      if(unidades == 7){
         string_units = "siete";
      }
      if(unidades == 8){
         string_units = "ocho";
      }
      if(unidades == 9){
         string_units = "nueve";
      }
       // end switch units
   } // end if-then-else
   

//final special cases. This conditions will handle the special cases which
//are not as general as the ones in the cascades. Basically four:

// when you've got 100, you dont' say 'ciento' you say 'cien'
// 'ciento' is used only for [101 >= number > 199]
if (centenas == 1 && decenas == 0 && unidades == 0)
{
   string_hundreds = "cien " ;
}  

// when you've got 10, you don't say any of the 11-19 special
// cases.. just say 'diez'
if (decenas == 1 && unidades ==0)
{
   string_tens = "diez " ;
}

// when you've got 20, you don't say 'veinti', which is used
// only for [21 >= number > 29]
if (decenas == 2 && unidades ==0)
{
  string_tens = "veinte " ;
}

// for numbers >= 30, you don't use a single word such as veintiuno
// (twenty one), you must add 'y' (and), and use two words. v.gr 31
// 'treinta y uno' (thirty and one)
if (decenas >=3 && unidades >=1)
{
   string_tens = string_tens+" y ";
}

// this line gathers all the hundreds, tens and units into the final string
// and returns it as the function value.
final_string = string_hundreds+string_tens+string_units;


return final_string ;

} //end of function string_literal_conversion()================================

// handle some external special cases. Specially the millions, thousands
// and hundreds descriptors. Since the same rules apply to all number triads
// descriptions are handled outside the string conversion function, so it can
// be re used for each triad.


function covertirNumLetras(number)
{
   
  //number = number_format (number, 2);
   number1=number;
   //settype (number, "integer");
   cent = number1.split(".");  
   centavos = cent[1];
   
   
   if (centavos == 0 || centavos == undefined){
   centavos = "00";}

   if (number == 0 || number == "")
   { // if amount = 0, then forget all about conversions,
      centenas_final_string=" cero "; // amount is zero (cero). handle it externally, to
      // function breakdown
  }
   else
   {
   
     millions  = ObtenerParteEntDiv(number, 1000000); // first, send the millions to the string
      number = mod(number, 1000000);           // conversion function
     
     if (millions != 0)
      {                      
      // This condition handles the plural case
         if (millions == 1)
         {              // if only 1, use 'millon' (million). if
            descriptor= " millon ";  // > than 1, use 'millones' (millions) as
            }
         else
         {                           // a descriptor for this triad.
              descriptor = " millones ";
            }
      }
      else
      {    
         descriptor = " ";                 // if 0 million then use no descriptor.
      }
      millions_final_string = string_literal_conversion(millions)+descriptor;
         
     
      thousands = ObtenerParteEntDiv(number, 1000);  // now, send the thousands to the string
        number = mod(number, 1000);            // conversion function.
      //print "Th:".thousands;
     if (thousands != 1)
      {                   // This condition eliminates the descriptor
         thousands_final_string =string_literal_conversion(thousands) + " mil ";
       //  descriptor = " mil ";          // if there are no thousands on the amount
      }
      if (thousands == 1)
      {
         thousands_final_string = " mil ";
     }
      if (thousands < 1)
      {
         thousands_final_string = " ";
      }
 
      // this will handle numbers between 1 and 999 which
      // need no descriptor whatsoever.

     centenas  = number;                    
      centenas_final_string = string_literal_conversion(centenas) ;
     
   } //end if (number ==0)

   /*if (ereg("un",centenas_final_string))
   {
     centenas_final_string = ereg_replace("","o",centenas_final_string);
   }*/

   //finally, print the output.

   /* Concatena los millones, miles y cientos*/
   cad = millions_final_string+thousands_final_string+centenas_final_string;
   
   /* Convierte la cadena a Mayúsculas*/
   cad = cad.toUpperCase();      

   if (centavos.length>2)
   {  
      if(centavos.substring(2,3)>= 5){
         centavos = centavos.substring(0,1)+(parseInt(centavos.substring(1,2))+1).toString();
      }   else{
        centavos = centavos.substring(0,2);
       }
   }

   /* Concatena a los centavos la cadena "/100" */
   if (centavos.length==1)
   {
      centavos = centavos+"0";
   }
   centavos = centavos+ "/100";


   /* Asigna el tipo de moneda, para 1 = PESO, para distinto de 1 = PESOS*/
   if (number == 1)
   {
      moneda = " PESO ";  
   }
   else
   {
      moneda = " PESOS ";  
   }
   /* Regresa el número en cadena entre paréntesis y con tipo de moneda y la fase M.N.*/
   alert( "FINAL="+cad+moneda+centavos+" 00/100 M.N. )");
}


</script>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>

<body>

<script> covertirNumLetras("3.20");</script>
</body>
</html>


Nota Vie Ago 20, 2010 1:47 pm

Perlero Nuevo
Registrado: Vie Ago 20, 2010 12:32 pm
Mensajes: 2
Re: Convertir números a letras  RESUELTO
Hola, buscando en la red una manera de convertir cantidades numéricas a letras encontré tu script, el cual está muy bueno, solo con el error que mencionas. Así que me di a la tarea de revisar el código, y encontré la respuesta, en la parte de abajo separas los centavos del número para redondearlos y trabajarlos a parte:
Syntax: [ Download ] [ Hide ]
Using javascript Syntax Highlighting
number1 = number;
cent = number1.split(".");  
centavos = cent[1];
 


El problema radica en que si ya separaste los centavos, no sobreescribes la variable "number" para dejar solo el número entero, la dejas tal cual con centavos. La función original por lo visto no estaba pensada para usar centavos puesto que hay una función que hace un "math.round" y como le dejas los centavos redondea el número.

Para corregir el error basta con agregar esta línea después de "centavos = cent[1];"
Syntax: [ Download ] [ Hide ]
Using javascript Syntax Highlighting
//Mind Mod
number = cent[0];
 


Con esto ya no habrá el problema del número redondeado.

Ya sé que el tema es muy viejo y a lo mejor ya resolviste el problema, pero a lo mejor alguien más como yo necesita esta función y se topa con el post. De esta manera ya podrá encontrarla lista para usar.

Aquí pongo de nuevo el código completo ya corregido y con unas modificaciones para el caso de 1000 pesos.

Saludos.

Syntax: [ Download ] [ Hide ]
Using javascript Syntax Highlighting
  1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  2. <html xmlns="http://www.w3.org/1999/xhtml">
  3. <head>
  4.  
  5. <script language="javascript">
  6.  
  7. // Función modulo, regresa el residuo de una división
  8. function mod(dividendo , divisor)
  9. {
  10.   resDiv = dividendo / divisor ;  
  11.   parteEnt = Math.floor(resDiv);            // Obtiene la parte Entera de resDiv
  12.   parteFrac = resDiv - parteEnt ;      // Obtiene la parte Fraccionaria de la división
  13.   //modulo = parteFrac * divisor;  // Regresa la parte fraccionaria * la división (modulo)
  14.   modulo = Math.round(parteFrac * divisor)
  15.   return modulo;
  16. } // Fin de función mod
  17.  
  18. // Función ObtenerParteEntDiv, regresa la parte entera de una división
  19. function ObtenerParteEntDiv(dividendo , divisor)
  20. {
  21.   resDiv = dividendo / divisor ;  
  22.   parteEntDiv = Math.floor(resDiv);
  23.   return parteEntDiv;
  24. } // Fin de función ObtenerParteEntDiv
  25.  
  26. // function fraction_part, regresa la parte Fraccionaria de una cantidad
  27. function fraction_part(dividendo , divisor)
  28. {
  29.   resDiv = dividendo / divisor ;  
  30.   f_part = Math.floor(resDiv);
  31.   return f_part;
  32. } // Fin de función fraction_part
  33.  
  34.  
  35. // function string_literal conversion is the core of this program
  36. // converts numbers to spanish strings, handling the general special
  37. // cases in spanish language.
  38. function string_literal_conversion(number)
  39. {  
  40.    // first, divide your number in hundreds, tens and units, cascadig
  41.    // trough subsequent divisions, using the modulus of each division
  42.    // for the next.
  43.  
  44.    centenas = ObtenerParteEntDiv(number, 100);
  45.    
  46.    number = mod(number, 100);
  47.  
  48.    decenas = ObtenerParteEntDiv(number, 10);
  49.    number = mod(number, 10);
  50.  
  51.    unidades = ObtenerParteEntDiv(number, 1);
  52.    number = mod(number, 1);  
  53.    string_hundreds="";
  54.    string_tens="";
  55.    string_units="";
  56.    // cascade trough hundreds. This will convert the hundreds part to
  57.    // their corresponding string in spanish.
  58.    if(centenas == 1){
  59.       string_hundreds = "ciento ";
  60.    }
  61.    
  62.    
  63.    if(centenas == 2){
  64.       string_hundreds = "doscientos ";
  65.    }
  66.    
  67.    if(centenas == 3){
  68.       string_hundreds = "trescientos ";
  69.    }
  70.    
  71.    if(centenas == 4){
  72.       string_hundreds = "cuatrocientos ";
  73.    }
  74.    
  75.    if(centenas == 5){
  76.       string_hundreds = "quinientos ";
  77.    }
  78.    
  79.    if(centenas == 6){
  80.       string_hundreds = "seiscientos ";
  81.    }
  82.    
  83.    if(centenas == 7){
  84.       string_hundreds = "setecientos ";
  85.    }
  86.    
  87.    if(centenas == 8){
  88.       string_hundreds = "ochocientos ";
  89.    }
  90.    
  91.    if(centenas == 9){
  92.       string_hundreds = "novecientos ";
  93.    }
  94.    
  95.  // end switch hundreds
  96.  
  97.    // casgade trough tens. This will convert the tens part to corresponding
  98.    // strings in spanish. Note, however that the strings between 11 and 19
  99.    // are all special cases. Also 21-29 is a special case in spanish.
  100.    if(decenas == 1){
  101.       //Special case, depends on units for each conversion
  102.       if(unidades == 1){
  103.          string_tens = "once";
  104.       }
  105.      
  106.       if(unidades == 2){
  107.          string_tens = "doce";
  108.       }
  109.      
  110.       if(unidades == 3){
  111.          string_tens = "trece";
  112.       }
  113.      
  114.       if(unidades == 4){
  115.          string_tens = "catorce";
  116.       }
  117.      
  118.       if(unidades == 5){
  119.          string_tens = "quince";
  120.       }
  121.      
  122.       if(unidades == 6){
  123.          string_tens = "dieciseis";
  124.       }
  125.      
  126.       if(unidades == 7){
  127.          string_tens = "diecisiete";
  128.       }
  129.      
  130.       if(unidades == 8){
  131.          string_tens = "dieciocho";
  132.       }
  133.      
  134.       if(unidades == 9){
  135.          string_tens = "diecinueve";
  136.       }
  137.    }
  138.    //alert("STRING_TENS ="+string_tens);
  139.    
  140.    if(decenas == 2){
  141.       string_tens = "veinti";
  142.  
  143.    }
  144.    if(decenas == 3){
  145.       string_tens = "treinta";
  146.    }
  147.    if(decenas == 4){
  148.       string_tens = "cuarenta";
  149.    }
  150.    if(decenas == 5){
  151.       string_tens = "cincuenta";
  152.    }
  153.    if(decenas == 6){
  154.       string_tens = "sesenta";
  155.    }
  156.    if(decenas == 7){
  157.       string_tens = "setenta";
  158.    }
  159.    if(decenas == 8){
  160.       string_tens = "ochenta";
  161.    }
  162.    if(decenas == 9){
  163.       string_tens = "noventa";
  164.    }
  165.    
  166.     // Fin de swicth decenas
  167.  
  168.  
  169.    // cascades trough units, This will convert the units part to corresponding
  170.    // strings in spanish. Note however that a check is being made to see wether
  171.    // the special cases 11-19 were used. In that case, the whole conversion of
  172.    // individual units is ignored since it was already made in the tens cascade.
  173.  
  174.    if (decenas == 1)
  175.    {
  176.       string_units="";  // empties the units check, since it has alredy been handled on the tens switch
  177.    }
  178.    else
  179.    {
  180.       if(unidades == 1){
  181.          string_units = "un";
  182.       }
  183.       if(unidades == 2){
  184.          string_units = "dos";
  185.       }
  186.       if(unidades == 3){
  187.          string_units = "tres";
  188.       }
  189.       if(unidades == 4){
  190.          string_units = "cuatro";
  191.       }
  192.       if(unidades == 5){
  193.          string_units = "cinco";
  194.       }
  195.       if(unidades == 6){
  196.          string_units = "seis";
  197.       }
  198.       if(unidades == 7){
  199.          string_units = "siete";
  200.       }
  201.       if(unidades == 8){
  202.          string_units = "ocho";
  203.       }
  204.       if(unidades == 9){
  205.          string_units = "nueve";
  206.       }
  207.        // end switch units
  208.    } // end if-then-else
  209.    
  210.  
  211. //final special cases. This conditions will handle the special cases which
  212. //are not as general as the ones in the cascades. Basically four:
  213.  
  214. // when you've got 100, you dont' say 'ciento' you say 'cien'
  215. // 'ciento' is used only for [101 >= number > 199]
  216. if (centenas == 1 && decenas == 0 && unidades == 0)
  217. {
  218.    string_hundreds = "cien " ;
  219. }  
  220.  
  221. // when you've got 10, you don't say any of the 11-19 special
  222. // cases.. just say 'diez'
  223. if (decenas == 1 && unidades ==0)
  224. {
  225.    string_tens = "diez " ;
  226. }
  227.  
  228. // when you've got 20, you don't say 'veinti', which is used
  229. // only for [21 >= number > 29]
  230. if (decenas == 2 && unidades ==0)
  231. {
  232.   string_tens = "veinte " ;
  233. }
  234.  
  235. // for numbers >= 30, you don't use a single word such as veintiuno
  236. // (twenty one), you must add 'y' (and), and use two words. v.gr 31
  237. // 'treinta y uno' (thirty and one)
  238. if (decenas >=3 && unidades >=1)
  239. {
  240.    string_tens = string_tens+" y ";
  241. }
  242.  
  243. // this line gathers all the hundreds, tens and units into the final string
  244. // and returns it as the function value.
  245. final_string = string_hundreds+string_tens+string_units;
  246.  
  247.  
  248. return final_string ;
  249.  
  250. } //end of function string_literal_conversion()================================
  251.  
  252. // handle some external special cases. Specially the millions, thousands
  253. // and hundreds descriptors. Since the same rules apply to all number triads
  254. // descriptions are handled outside the string conversion function, so it can
  255. // be re used for each triad.
  256.  
  257.  
  258. function covertirNumLetras(number)
  259. {
  260.    
  261.   //number = number_format (number, 2);
  262.    number1=number;
  263.    //settype (number, "integer");
  264.    cent = number1.split(".");  
  265.    centavos = cent[1];
  266.    //Mind Mod
  267.    number=cent[0];
  268.    
  269.    if (centavos == 0 || centavos == undefined)
  270.    {
  271.         centavos = "00";
  272.    }
  273.  
  274.    if (number == 0 || number == "")
  275.    { // if amount = 0, then forget all about conversions,
  276.       centenas_final_string=" cero "; // amount is zero (cero). handle it externally, to
  277.       // function breakdown
  278.   }
  279.    else
  280.    {
  281.    
  282.      millions  = ObtenerParteEntDiv(number, 1000000); // first, send the millions to the string
  283.       number = mod(number, 1000000);           // conversion function
  284.      
  285.      if (millions != 0)
  286.       {                      
  287.       // This condition handles the plural case
  288.          if (millions == 1)
  289.          {              // if only 1, use 'millon' (million). if
  290.             descriptor= " millon ";  // > than 1, use 'millones' (millions) as
  291.             }
  292.          else
  293.          {                           // a descriptor for this triad.
  294.               descriptor = " millones ";
  295.             }
  296.       }
  297.       else
  298.       {    
  299.          descriptor = " ";                 // if 0 million then use no descriptor.
  300.       }
  301.       millions_final_string = string_literal_conversion(millions)+descriptor;
  302.          
  303.      
  304.       thousands = ObtenerParteEntDiv(number, 1000);  // now, send the thousands to the string
  305.         number = mod(number, 1000);            // conversion function.
  306.       //print "Th:".thousands;
  307.      if (thousands != 1)
  308.       {                   // This condition eliminates the descriptor
  309.          thousands_final_string =string_literal_conversion(thousands) + " mil ";
  310.        //  descriptor = " mil ";          // if there are no thousands on the amount
  311.       }
  312.       if (thousands == 1)
  313.       {
  314.          thousands_final_string = " mil ";
  315.      }
  316.       if (thousands < 1)
  317.       {
  318.          thousands_final_string = " ";
  319.       }
  320.  
  321.       // this will handle numbers between 1 and 999 which
  322.       // need no descriptor whatsoever.
  323.  
  324.      centenas  = number;                    
  325.       centenas_final_string = string_literal_conversion(centenas) ;
  326.      
  327.    } //end if (number ==0)
  328.  
  329.    /*if (ereg("un",centenas_final_string))
  330.    {
  331.      centenas_final_string = ereg_replace("","o",centenas_final_string);
  332.    }*/
  333.    //finally, print the output.
  334.  
  335.    /* Concatena los millones, miles y cientos*/
  336.    cad = millions_final_string+thousands_final_string+centenas_final_string;
  337.    
  338.    /* Convierte la cadena a Mayúsculas*/
  339.    cad = cad.toUpperCase();      
  340.  
  341.    if (centavos.length>2)
  342.    {  
  343.        
  344.       if(centavos.substring(2,3)>= 5){
  345.          centavos = centavos.substring(0,1)+(parseInt(centavos.substring(1,2))+1).toString();
  346.       }   else{
  347.          
  348.         centavos = centavos.substring(0,1);
  349.       }
  350.    }
  351.  
  352.    /* Concatena a los centavos la cadena "/100" */
  353.    if (centavos.length==1)
  354.    {
  355.       centavos = centavos+"0";
  356.    }
  357.    centavos = centavos+ "/100";
  358.  
  359.  
  360.    /* Asigna el tipo de moneda, para 1 = PESO, para distinto de 1 = PESOS*/
  361.    if (number == 1)
  362.    {
  363.       moneda = " PESO ";  
  364.    }
  365.    else
  366.    {
  367.       moneda = " PESOS ";  
  368.    }
  369.    /* Regresa el número en cadena entre paréntesis y con tipo de moneda y la fase M.N.*/
  370.    //Mind Mod, si se deja MIL pesos y se utiliza esta función para imprimir documentos
  371.    //de caracter legal, dejar solo MIL es incorrecto, para evitar fraudes se debe de poner UM MIL pesos
  372.    if(cad == '  MIL ')
  373.    {
  374.         cad=' UN MIL ';
  375.    }
  376.    
  377.    alert( "FINAL="+cad+moneda+centavos+" M.N.");
  378.    return cad+moneda+centavos+" M.N.";
  379. }
  380.  
  381.  
  382. </script>
  383.  
  384. <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  385. <title>Untitled Document</title>
  386. </head>
  387.  
  388. <body>
  389. //Mind Mod - numero de 12 millones con varios decimales para que comprueben su efectividad
  390. <script> covertirNumLetras("12456789.459786");</script>
  391. </body>
  392. </html>
  393.  


Nota Vie Ago 20, 2010 2:45 pm

Perlero Nuevo
Registrado: Vie Sep 12, 2008 9:36 am
Mensajes: 16
Re: Convertir números a letras
No que va te agradezco, en nombre pienso yo de todos los demás internautas.

En efecto este problema lo tuve hace tiempo y nunca llegué a resolverlo: opté por utilizar un módulo de Perl que me facilitó la tarea. De todos modos estoy copiando tu solución para guardarla en mi PC: nunca se sabe cuándo volverás a utilizarlo.

Muchas gracias, de verdad.


Nota Vie Ago 20, 2010 3:01 pm

Perlero Nuevo
Registrado: Vie Ago 20, 2010 12:32 pm
Mensajes: 2
Re: Convertir números a letras
De nada, espero que esto sea de ayuda para alguien más, como lo fue para mi, el script que publicaste me ahorró mucho tiempo, lo mínimo que podía hacer era contribuir para que ayude a alguien más.


Nota Dom Sep 26, 2010 1:35 pm

Perlero Nuevo
Registrado: Dom Sep 26, 2010 12:44 pm
Mensajes: 1
Re: Convertir números a letras
Es ahora que necesité rápidamente hacer esta conversión para una plantilla de factura. Les agradezco que lo hayan publicado, ya que me sacó de apuros. Al implementarlo encontré un "medio error"... se trata de que la función function convertirNumLetras(number) {} interpreta el [i]number[/i] como [i]string[/i] y falta convertir el valor en [i]string[/i].

Aquí está mi modificación:
Syntax: [ Download ] [ Hide ]
Using javascript Syntax Highlighting
number1=number.toString();

En lugar de:
Syntax: [ Download ] [ Hide ]
Using javascript Syntax Highlighting
  1. number1=number;


Para capturar el valor de una variable de otro lenguaje (PHP, Python, etc) le agregué esta función y lo relacioné con el evento "onLoad" en el BODY:

Syntax: [ Download ] [ Hide ]
Using javascript Syntax Highlighting
  1. function doSpanish(importe) {
  2.     document.getElementById('spn').innerHTML='( '+convertirNumLetras(importe)+ ' )';
  3.         return true;
  4.     }


Contenido HTML:

Syntax: [ Download ] [ Hide ]
Using javascript Syntax Highlighting
  1. <body onLoad="doSpanish($variabilaValue)">
  2.                 <div id="spn" style="float:left;margin:40px auto;">XXX</div>


Para estar más claro, aquí está todo con las modificaciones. Espero que les sirvan a otros también :)

Syntax: [ Download ] [ Hide ]
Using javascript Syntax Highlighting
  1. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
  2.    "http://www.w3.org/TR/html4/loose.dtd">
  3.  
  4. <html lang="en">
  5. <head>
  6.         <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
  7.         <title>Converción importe a letras</title>
  8.  
  9. <script type="application/javascript">
  10. // Función modulo, regresa el residuo de una división
  11. function mod(dividendo , divisor)
  12. {
  13.   resDiv = dividendo / divisor ;  
  14.   parteEnt = Math.floor(resDiv);            // Obtiene la parte Entera de resDiv
  15.   parteFrac = resDiv - parteEnt ;      // Obtiene la parte Fraccionaria de la división
  16.   //modulo = parteFrac * divisor;  // Regresa la parte fraccionaria * la división (modulo)
  17.   modulo = Math.round(parteFrac * divisor)
  18.   return modulo;
  19. }
  20. // Fin de función mod
  21.  
  22. // Función ObtenerParteEntDiv, regresa la parte entera de una división
  23. function ObtenerParteEntDiv(dividendo , divisor)
  24. {
  25.   resDiv = dividendo / divisor ;  
  26.   parteEntDiv = Math.floor(resDiv);
  27.   return parteEntDiv;
  28. }
  29. // Fin de función ObtenerParteEntDiv
  30.  
  31. // function fraction_part, regresa la parte Fraccionaria de una cantidad
  32. function fraction_part(dividendo , divisor)
  33. {
  34.   resDiv = dividendo / divisor ;  
  35.   f_part = Math.floor(resDiv);
  36.   return f_part;
  37. }
  38. // Fin de función fraction_part
  39.  
  40. // function string_literal conversion is the core of this program
  41. // converts numbers to spanish strings, handling the general special
  42. // cases in spanish language.
  43. function string_literal_conversion(number)
  44. {  
  45.    // first, divide your number in hundreds, tens and units, cascadig
  46.    // trough subsequent divisions, using the modulus of each division
  47.    // for the next.
  48.  
  49.    centenas = ObtenerParteEntDiv(number, 100);
  50.    number = mod(number, 100);
  51.    decenas = ObtenerParteEntDiv(number, 10);
  52.    number = mod(number, 10);
  53.  
  54.    unidades = ObtenerParteEntDiv(number, 1);
  55.    number = mod(number, 1);  
  56.    string_hundreds="";
  57.    string_tens="";
  58.    string_units="";
  59.    
  60.    // cascade trough hundreds. This will convert the hundreds part to
  61.    // their corresponding string in spanish.
  62.    if(centenas == 1){
  63.       string_hundreds = "ciento ";
  64.    }
  65.    if(centenas == 2){
  66.       string_hundreds = "doscientos ";
  67.    }
  68.    if(centenas == 3){
  69.       string_hundreds = "trescientos ";
  70.    }
  71.    if(centenas == 4){
  72.       string_hundreds = "cuatrocientos ";
  73.    }
  74.    if(centenas == 5){
  75.       string_hundreds = "quinientos ";
  76.    }
  77.    if(centenas == 6){
  78.       string_hundreds = "seiscientos ";
  79.    }
  80.    if(centenas == 7){
  81.       string_hundreds = "setecientos ";
  82.    }
  83.    if(centenas == <img src="http://perlenespanol.com/foro/images/smilies/icon_cool.gif" alt="8)" title="Cool" />{
  84.       string_hundreds = "ochocientos ";
  85.    }
  86.    if(centenas == 9){
  87.       string_hundreds = "novecientos ";
  88.    }
  89.  // end switch hundreds
  90.  
  91.    // casgade trough tens. This will convert the tens part to corresponding
  92.    // strings in spanish. Note, however that the strings between 11 and 19
  93.    // are all special cases. Also 21-29 is a special case in spanish.
  94.    if(decenas == 1){
  95.            
  96.       //Special case, depends on units for each conversion
  97.       if(unidades == 1){
  98.          string_tens = "once";
  99.       }
  100.       if(unidades == 2){
  101.          string_tens = "doce";
  102.       }
  103.       if(unidades == 3){
  104.          string_tens = "trece";
  105.       }
  106.       if(unidades == 4){
  107.          string_tens = "catorce";
  108.       }
  109.       if(unidades == 5){
  110.          string_tens = "quince";
  111.       }
  112.       if(unidades == 6){
  113.          string_tens = "dieciseis";
  114.       }
  115.       if(unidades == 7){
  116.          string_tens = "diecisiete";
  117.       }
  118.       if(unidades == <img src="http://perlenespanol.com/foro/images/smilies/icon_cool.gif" alt="8)" title="Cool" />{
  119.          string_tens = "dieciocho";
  120.       }
  121.       if(unidades == 9){
  122.          string_tens = "diecinueve";
  123.       }
  124.    }
  125.    //alert("STRING_TENS ="+string_tens);
  126.    
  127.    if(decenas == 2){
  128.       string_tens = "veinti";
  129.    }
  130.    if(decenas == 3){
  131.       string_tens = "treinta";
  132.    }
  133.    if(decenas == 4){
  134.       string_tens = "cuarenta";
  135.    }
  136.    if(decenas == 5){
  137.       string_tens = "cincuenta";
  138.    }
  139.    if(decenas == 6){
  140.       string_tens = "sesenta";
  141.    }
  142.    if(decenas == 7){
  143.       string_tens = "setenta";
  144.    }
  145.    if(decenas == <img src="http://perlenespanol.com/foro/images/smilies/icon_cool.gif" alt="8)" title="Cool" />{
  146.       string_tens = "ochenta";
  147.    }
  148.    if(decenas == 9){
  149.       string_tens = "noventa";
  150.    }
  151.     // Fin of swicth decenas
  152.  
  153.    // cascades trough units, This will convert the units part to corresponding
  154.    // strings in spanish. Note however that a check is being made to see wether
  155.    // the special cases 11-19 were used. In that case, the whole conversion of
  156.    // individual units is ignored since it was already made in the tens cascade.
  157.    if (decenas == 1)
  158.    {
  159.       string_units="";  
  160.           // empties the units check, since it has alredy been handled on the tens switch
  161.    }
  162.    else
  163.    {
  164.       if(unidades == 1){
  165.          string_units = "un";
  166.       }
  167.       if(unidades == 2){
  168.          string_units = "dos";
  169.       }
  170.       if(unidades == 3){
  171.          string_units = "tres";
  172.       }
  173.       if(unidades == 4){
  174.          string_units = "cuatro";
  175.       }
  176.       if(unidades == 5){
  177.          string_units = "cinco";
  178.       }
  179.       if(unidades == 6){
  180.          string_units = "seis";
  181.       }
  182.       if(unidades == 7){
  183.          string_units = "siete";
  184.       }
  185.       if(unidades == <img src="http://perlenespanol.com/foro/images/smilies/icon_cool.gif" alt="8)" title="Cool" />{
  186.          string_units = "ocho";
  187.       }
  188.       if(unidades == 9){
  189.          string_units = "nueve";
  190.       }
  191.        // end switch units
  192.    } // end if-then-else
  193. //final special cases. This conditions will handle the special cases which
  194. //are not as general as the ones in the cascades. Basically four:
  195.  
  196. // when you've got 100, you dont' say 'ciento' you say 'cien'
  197. // 'ciento' is used only for [101 >= number > 199]
  198. if (centenas == 1 && decenas == 0 && unidades == 0)
  199. {
  200.    string_hundreds = "cien " ;
  201. }  
  202. // when you've got 10, you don't say any of the 11-19 special
  203. // cases.. just say 'diez'
  204. if (decenas == 1 && unidades ==0)
  205. {
  206.    string_tens = "diez " ;
  207. }
  208. // when you've got 20, you don't say 'veinti', which is used
  209. // only for [21 >= number > 29]
  210. if (decenas == 2 && unidades ==0)
  211. {
  212.   string_tens = "veinte " ;
  213. }
  214. // for numbers >= 30, you don't use a single word such as veintiuno
  215. // (twenty one), you must add 'y' (and), and use two words. v.gr 31
  216. // 'treinta y uno' (thirty and one)
  217. if (decenas >=3 && unidades >=1)
  218. {
  219.    string_tens = string_tens+" y ";
  220. }
  221. // this line gathers all the hundreds, tens and units into the final string
  222. // and returns it as the function value.
  223. final_string = string_hundreds+string_tens+string_units;
  224. return final_string ;
  225. }
  226. //end of function string_literal_conversion
  227. // handle some external special cases. Specially the millions, thousands
  228. // and hundreds descriptors. Since the same rules apply to all number triads
  229. // descriptions are handled outside the string conversion function, so it can
  230. // be re used for each triad.
  231. function convertirNumLetras(number)
  232. {
  233.   //number = number_format (number, 2);
  234.    number1=number.toString();
  235.    //settype (number, "integer");
  236.    cent = number1.split(".");  
  237.    centavos = cent[1];
  238.    //Mind Mod
  239.    number=cent[0];
  240.    if (centavos == 0 || centavos == undefined)
  241.    {
  242.         centavos = "00";
  243.    }
  244.    if (number == 0 || number == "")
  245.    { // if amount = 0, then forget all about conversions,
  246.       centenas_final_string=" cero "; // amount is zero (cero). handle it externally, to
  247.       // function breakdown
  248.   }
  249.    else
  250.    {
  251.      millions  = ObtenerParteEntDiv(number, 1000000); // first, send the millions to the string
  252.       number = mod(number, 1000000);           // conversion function
  253.      
  254.      if (millions != 0)
  255.       {                      
  256.       // This condition handles the plural case
  257.          if (millions == 1)
  258.          {              // if only 1, use 'millon' (million). if
  259.             descriptor= " millon ";  // > than 1, use 'millones' (millions) as
  260.             }
  261.          else
  262.          {                           // a descriptor for this triad.
  263.               descriptor = " millones ";
  264.             }
  265.       }
  266.       else
  267.       {    
  268.          descriptor = " ";                 // if 0 million then use no descriptor.
  269.       }
  270.       millions_final_string = string_literal_conversion(millions)+descriptor;
  271.       thousands = ObtenerParteEntDiv(number, 1000);  // now, send the thousands to the string
  272.         number = mod(number, 1000);            // conversion function.
  273.       //print "Th:".thousands;
  274.      if (thousands != 1)
  275.       {                   // This condition eliminates the descriptor
  276.          thousands_final_string =string_literal_conversion(thousands) + " mil ";
  277.        //  descriptor = " mil ";          // if there are no thousands on the amount
  278.       }
  279.       if (thousands == 1)
  280.       {
  281.          thousands_final_string = " mil ";
  282.      }
  283.       if (thousands < 1)
  284.       {
  285.          thousands_final_string = " ";
  286.       }
  287.       // this will handle numbers between 1 and 999 which
  288.       // need no descriptor whatsoever.
  289.      centenas  = number;                    
  290.       centenas_final_string = string_literal_conversion(centenas) ;
  291.    } //end if (number ==0)
  292.  
  293.    /*if (ereg("un",centenas_final_string))
  294.    {
  295.      centenas_final_string = ereg_replace("","o",centenas_final_string);
  296.    }*/
  297.    //finally, print the output.
  298.  
  299.    /* Concatena los millones, miles y cientos*/
  300.    cad = millions_final_string+thousands_final_string+centenas_final_string;
  301.    /* Convierte la cadena a Mayúsculas*/
  302.    cad = cad.toUpperCase();      
  303.    if (centavos.length>2)
  304.    {  
  305.       if(centavos.substring(2,3)>= 5){
  306.          centavos = centavos.substring(0,1)+(parseInt(centavos.substring(1,2))+1).toString();
  307.       }   else{
  308.          
  309.         centavos = centavos.substring(0,1);
  310.       }
  311.    }
  312.  
  313.    /* Concatena a los centavos la cadena "/100" */
  314.    if (centavos.length==1)
  315.    {
  316.       centavos = centavos+"0";
  317.    }
  318.    centavos = centavos+ "/100";
  319.  
  320.  
  321.    /* Asigna el tipo de moneda, para 1 = PESO, para distinto de 1 = PESOS*/
  322.    if (number == 1)
  323.    {
  324.       moneda = " PESO ";  
  325.    }
  326.    else
  327.    {
  328.       moneda = " PESOS ";  
  329.    }
  330.    /* Regresa el número en cadena entre paréntesis y con tipo de moneda y la fase M.N.*/
  331.    //Mind Mod, si se deja MIL pesos y se utiliza esta función para imprimir documentos
  332.    //de caracter legal, dejar solo MIL es incorrecto, para evitar fraudes se debe de poner UM MIL pesos
  333.    if(cad == '  MIL ')
  334.    {
  335.         cad=' UN MIL ';
  336.    }
  337.   // alert( "FINAL="+cad+moneda+centavos+" M.N.");
  338.   return cad+moneda+centavos+" M.N.";
  339. }
  340. function doSpanish(importe) {
  341.         document.getElementById('spn').innerHTML='( '+convertirNumLetras(importe)+ ' )';
  342.                 return true;
  343.         }
  344. </script>
  345. </head>
  346. <body onLoad="doSpanish($variabilaValue)">
  347.                 <div id="spn" style="float:left;margin:40px auto;">XXX</div>
  348. </body>
  349. </html>


Responder al tema  [ 5 mensajes ] 

Reglas del Foro
No puedes abrir nuevos temas en este Foro
No puedes responder a temas en este Foro
No puedes editar tus mensajes en este Foro
No puedes borrar tus mensajes en este Foro
No puedes enviar adjuntos en este Foro

Publicidad

Socializa

Síguenos por Twitter

Suscríbete GRATUITAMENTE al Boletín de Perl en Español

Saltar a:  
Powered by phpBB © 2000, 2002, 2005, 2007 phpBB Group
Traducción al español por Huan Manwë para phpbb-es.com
phpBB SEO