Comunidad de diseño web y desarrollo en internet online

convertir numeros a letras

Citar            
MensajeEscrito el 03 Nov 2008 03:11 am
amigos: en este mismo foro, pero hace ya varios años, publicaron el script que copio a continuacion. Sirve para convertir numeros o monedas en letras. De veras sirve, pero tiene un error.
Por ejemplo para un numero como 34.49 el resultado es: treinta y cuatro con cuarenta y nueve. OK
Pero si pasa la mitad, o sea 34.51 arroja treinta y cinco con cincuenta y uno.

Alguien puede indicarme el error y corregirlo para que le sirva a otros forista tambien?
GRACIAS DE ANTEMANO
EL CODIGO:

<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 = " NUEVO SOL ";
}
else
{
moneda = " NUEVOS SOLES ";
}
/* Regresa el número en cadena entre paréntesis y con tipo de moneda y la fase M.N.*/
document.write( "FINAL="+cad+moneda+centavos+" 00/100 M.N. )");
}


</script>

Por luisbal

2 de clabLevel



 

msie7
Citar            
MensajeEscrito el 24 Feb 2009 03:23 pm
Amigo, no se si ta te respondieron.

Estoy intentando hacer lo mismo que tu, e visto tu código y me parece que esta bien ahora como soy nuevo en esto en verdad no encuentro la forma de pasarlea la función en número, puedes darme una mano.

Este es el achivo que intento probar junto con tu función de JavaScript:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>Pruebas de Número a Letras</title>
<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 = "DIECISÉIS ";
}

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 = "CUARENBTE ";
}
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 = number.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= " MILLÓN "; // > 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*/

moneda = " Bs. ";
/* Regresa el número en cadena entre paréntesis y con tipo de moneda y la fase M.N.*/
document.write( "FINAL = "+cad+moneda+centavos+" 00/100 )");
}
</script>
</head>

<body>
<input name="num" type="text" size="16" maxlength="16" id="num" />

<a href="#" onclick="covertirNumLetras();"> Convertir </a>
</body>
</html>

Por hoviedo

0 de clabLevel



 

msie7
Citar            
MensajeEscrito el 28 Oct 2010 06:09 am
Hola si esta código hace años salio y tenia más defectos que corregí y no publique y se daño mi disco duro pero trabajo para recuperar las librerías y esta vez buscando el tiempo para compartirlas igual. La buena noticia es que ya detecte el error y es el siguiente:

modulo = Math.round(parteFrac * divisor); // Regresa la parte fraccionaria * la división (modulo)
esto esta en la función: mod(dividendo , divisor)
debemos dejarlo como sigue:

// 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 =(parteFrac * divisor); // Regresa la parte fraccionaria * la división (modulo)
return modulo;
} // Fin de función mod

Lo único que aquí hacemos es eliminar el Math.round con eso evitamos que redondee que mas que un error es un proceso de funcionamiento pero que no nos sirve para el fin común que tenemos espero les sea de ayuda hasta pronto.

Por CLAnonimo

Claber

600 de clabLevel

5 tutoriales
1 articulo

 

Este es un usuario anónimo genérico para las cuentas borradas o perdidas.

chrome

 

Cristalab BabyBlue v4 + V4 © 2011 Cristalab
Powered by ClabEngines v4, HTML5, love and ponies.