Foros del Web » Programando para Internet » Javascript »

sumar decimales no se puede con esta fucion

Estas en el tema de sumar decimales no se puede con esta fucion en el foro de Javascript en Foros del Web. hola foro que tal pues tome esta exelente funcion que pone las cantidades fabulosamente pero el problema es al momento de sumarlos son parseFloat() no ...
  #1 (permalink)  
Antiguo 24/11/2005, 11:28
Avatar de The_omars  
Fecha de Ingreso: marzo-2004
Mensajes: 271
Antigüedad: 20 años, 1 mes
Puntos: 0
sumar decimales no se puede con esta fucion

hola foro que tal pues tome esta exelente funcion que pone las cantidades fabulosamente pero el problema es al momento de sumarlos son parseFloat()
no me pone los decimales.
por ejemplo cuando sumo 2,000.00 + 2,500.00 no me funciona.

esta es la funcion:

Código PHP:
<html
<
head
  <
script language="JavaScript"
   function 
currencyFormat(fldmilSepdecSepe) { 
    var 
sep 0
    var 
key ''
    var 
0
    var 
len len2 0
    var 
strCheck '0123456789'
    var 
aux aux2 ''
    var 
whichCode = (window.Event) ? e.which e.keyCode
    if (
whichCode == 13) return true// Enter 
    
key String.fromCharCode(whichCode); // Get key value from key code 
    
if (strCheck.indexOf(key) == -1) return false// Not a valid key 
    
len fld.value.length
    for(
0leni++) 
     if ((
fld.value.charAt(i) != '0') && (fld.value.charAt(i) != decSep)) break; 
    
aux ''
    for(; 
leni++) 
     if (
strCheck.indexOf(fld.value.charAt(i))!=-1aux += fld.value.charAt(i); 
    
aux += key
    
len aux.length
    if (
len == 0fld.value ''
    if (
len == 1fld.value '0'decSep '0' aux
    if (
len == 2fld.value '0'decSep aux
    if (
len 2) { 
     
aux2 ''
     for (
0len 3>= 0i--) { 
      if (
== 3) { 
       
aux2 += milSep
       
0
      } 
      
aux2 += aux.charAt(i); 
      
j++; 
     } 
     
fld.value ''
     
len2 aux2.length
     for (
len2 1>= 0i--) 
      
fld.value += aux2.charAt(i); 
     
fld.value += decSep aux.substr(len 2len); 
    } 
    return 
false
   } 
   
  function 
sumar(){
  
t1=document.all["test1"].value;
  
t2=document.all["test2"].value;
  
ftota=parseFloat(t1) + parseFloat(t2);
  
document.all["res"].value=ftota;
  } 
  
</script> 
</head> 
<body> 
  <form> 
  <table>
  <th>
   Tipee un número: </th>
   <tr><td><input type="text" name="test1" length="15" onKeyPress="return(currencyFormat(this,',','.',event))"> 
   <tr><td><input type="text" name="test2" length="15" onKeyPress="return(currencyFormat(this,',','.',event))"> 
   <tr><td><input type="button" onClick="sumar()" value="SUMAR">
   <tr><td>Resutado<input type="text"  name="res">
   </table>
  </form> 
</body> 
</html> 
por su ayuda de antemano muchas gracias
  #2 (permalink)  
Antiguo 24/11/2005, 13:10
 
Fecha de Ingreso: octubre-2004
Ubicación: España
Mensajes: 894
Antigüedad: 19 años, 6 meses
Puntos: 3
Hola, The_omars
No puedes sumar los números con ese formato, no los entiende como números. Deberían ser
2000.00 + 2500.00

Puedes hacer una función que quite las comas antes de sumar.
__________________
Angel :cool:
  #3 (permalink)  
Antiguo 24/11/2005, 14:25
Avatar de The_omars  
Fecha de Ingreso: marzo-2004
Mensajes: 271
Antigüedad: 20 años, 1 mes
Puntos: 0
hola si me falto ese detalle pero aun asi por ejepmlo sumando

50.00
+
40.00

me sale:

90 sin los decimales.

cheka el codigo y pruebalo
  #4 (permalink)  
Antiguo 24/11/2005, 14:40
 
Fecha de Ingreso: octubre-2004
Ubicación: España
Mensajes: 894
Antigüedad: 19 años, 6 meses
Puntos: 3
Pues claro, el ordenador no da formato a los números, tan sólo los calcula.
50.00 + 40.00 = 90
50.01 + 40.01 = 90.02
Si quieres un número fijo de decimales debes hacerlo tú con una función.

Código PHP:
<script type="text/javascript">
function 
decimales(NumeroDecimales) {
    
pot Math.pow(10,Decimales);
    
num Math.round(Numero pot) / pot;
    
nume num.toString().split('.');
    
entero nume[0];
    
decima nume[1];
    if (
decima != undefined) {
        
fin Decimales-decima.length; }
    else {
        
decima '';
        
fin Decimales; }
    for(
i=0;i<fin;i++)
      
decima+=String.fromCharCode(48); 
    
num=entero+'.'+decima;
    return 
num;
}
</script>
<form>
Fijar a <input type="text" name="dec" size="3">
decimales:
<input type="text" name="entrada">
<input type="button" value="Dar formato" onClick="this.form.salida.value=decimales(this.form.entrada.value,this.form.dec.value)">
<input type="text" name="salida">
</form> 
__________________
Angel :cool:
  #5 (permalink)  
Antiguo 24/11/2005, 14:44
Avatar de flaviovich  
Fecha de Ingreso: agosto-2005
Ubicación: Lima, Peru
Mensajes: 2.951
Antigüedad: 18 años, 8 meses
Puntos: 39
Por que no usas la funcion toFixed()?
__________________
No repitamos temas, usemos el Motor de busquedas
Plantea bien tu problema: Ayúdanos a ayudarte.
  #6 (permalink)  
Antiguo 24/11/2005, 15:22
 
Fecha de Ingreso: noviembre-2005
Mensajes: 3
Antigüedad: 18 años, 5 meses
Puntos: 0
HOLA SOY NUEVO EN EL FORO
ACTUALMENTE E PROGRAMADO COSAS MUY SIMPLE EN ACTION SCRIPT Y OTROS PROGRAMAS COMO EL QBASIC ETC
PERO EN JAVA NUNCA
QUIESIERA SABER COMO HACER UN ALBUN DE FOTO
VIRTUAL EN LA CUAL SE CARGUEN LAS FOTOS Y AL ACCIONAR UN BOTON SIGUIENTE SE VAYAN PASANDO LAS FOTOSY VAYAN DESAPARECIENDO EN ALFA ASTA QUE SE CARGUE LA OTRA QUIERO QUE ME EXPLIQUEN COMO ES EL LENGUAJE O DIRECTAMENTE ENVIENME UN TOTORIALS, MI MSN EN [email protected]
  #7 (permalink)  
Antiguo 24/11/2005, 16:48
 
Fecha de Ingreso: octubre-2004
Ubicación: España
Mensajes: 894
Antigüedad: 19 años, 6 meses
Puntos: 3
Cita:
Iniciado por flaviovich
Por que no usas la funcion toFixed()?
No la conocía. ¡Estupendo!

var num = 50.00 + 40.00
alert(num.toFixed(2))
__________________
Angel :cool:
  #8 (permalink)  
Antiguo 29/11/2005, 09:08
Avatar de The_omars  
Fecha de Ingreso: marzo-2004
Mensajes: 271
Antigüedad: 20 años, 1 mes
Puntos: 0
Heey muy buena pero no ha solucionado el problema.
ahora cuando multiplico 230.000.00 * 2 = 4.60 y no me pone los siguientes ceros.

esta es la operacion:

Código PHP:

v
=este.value// valor de text
cant=document.all["cantidad"].value// se multiplica x la cantidad
t=parseFloat(v) * parseFloat(cant); 
  #9 (permalink)  
Antiguo 29/11/2005, 09:31
Avatar de flaviovich  
Fecha de Ingreso: agosto-2005
Ubicación: Lima, Peru
Mensajes: 2.951
Antigüedad: 18 años, 8 meses
Puntos: 39
Y como distingues el decimal?
Quizas necesites Colocar separadores de miles y decimales mientras se escribe.
__________________
No repitamos temas, usemos el Motor de busquedas
Plantea bien tu problema: Ayúdanos a ayudarte.
  #10 (permalink)  
Antiguo 29/11/2005, 09:42
Avatar de The_omars  
Fecha de Ingreso: marzo-2004
Mensajes: 271
Antigüedad: 20 años, 1 mes
Puntos: 0
uso la siguiente funcion para sacar un formato.

Código PHP:
function currencyFormat(fldmilSepdecSepe) { 
    var 
sep 0
    var 
key ''
    var 
0
    var 
len len2 0
    var 
strCheck '0123456789'
    var 
aux aux2 ''
    var 
whichCode = (window.Event) ? e.which e.keyCode
    if (
whichCode == 13) return true// Enter 
    
key String.fromCharCode(whichCode); // Get key value from key code 
    
if (strCheck.indexOf(key) == -1) return false// Not a valid key 
    
len fld.value.length
    for(
0leni++) 
     if ((
fld.value.charAt(i) != '0') && (fld.value.charAt(i) != decSep)) break; 
    
aux ''
    for(; 
leni++) 
     if (
strCheck.indexOf(fld.value.charAt(i))!=-1aux += fld.value.charAt(i); 
    
aux += key
    
len aux.length
    if (
len == 0fld.value ''
    if (
len == 1fld.value '0'decSep '0' aux
    if (
len == 2fld.value '0'decSep aux
    if (
len 2) { 
     
aux2 ''
     for (
0len 3>= 0i--) { 
      if (
== 3) { 
       
aux2 += milSep
       
0
      } 
      
aux2 += aux.charAt(i); 
      
j++; 
     } 
     
fld.value ''
     
len2 aux2.length
     for (
len2 1>= 0i--) 
      
fld.value += aux2.charAt(i); 
     
fld.value += decSep aux.substr(len 2len); 
    } 
    return 
false
   } 
//

<input type=text name=loquesea onKeyPress="return(currencyFormat(this,'.','.',event))"

  #11 (permalink)  
Antiguo 29/11/2005, 13:52
 
Fecha de Ingreso: octubre-2004
Ubicación: España
Mensajes: 894
Antigüedad: 19 años, 6 meses
Puntos: 3
The_omars, no sé cómo funciona esa función, pero es evidente que si al ordenador le das un dato con dos puntos no puede distinguir cuál hace de decimal y cuál de separador de miles; o bien lo entiende como un texto o interpreta el primer punto como decimal y lo trunca (lo que está haciendo).
Si quieres hacer operaciones matemáticas, debes darle números en el formato estándar (punto decimal y sin separador de miles). El resto es una tarea de formateado que tú debes manipulándolo como texto, pero no vale para las operaciones.
__________________
Angel :cool:
  #12 (permalink)  
Antiguo 01/12/2005, 09:36
Avatar de The_omars  
Fecha de Ingreso: marzo-2004
Mensajes: 271
Antigüedad: 20 años, 1 mes
Puntos: 0
pues si mmmmmm. pero esa funcion es muy buena y es casi los que necesito.

que lastima. pues lo seguire intentando.






CARICATOS ,, HELP

Última edición por The_omars; 01/12/2005 a las 09:42
  #13 (permalink)  
Antiguo 01/12/2005, 16:06
 
Fecha de Ingreso: octubre-2004
Ubicación: España
Mensajes: 894
Antigüedad: 19 años, 6 meses
Puntos: 3
La función es para **presentar** el resultado, no para **calcularlo**.
Guarda los datos en una variable separada y usa la función sólo para mostrarlos.
__________________
Angel :cool:
Atención: Estás leyendo un tema que no tiene actividad desde hace más de 6 MESES, te recomendamos abrir un Nuevo tema en lugar de responder al actual.
Respuesta

SíEste tema le ha gustado a 1 personas




La zona horaria es GMT -6. Ahora son las 11:14.