Foros del Web » Programando para Internet » Javascript »

numeros decimales

Estas en el tema de numeros decimales en el foro de Javascript en Foros del Web. necesito realizar una suma de producto en la base de datos tengo el valor por ejemplo 120.000 y en el subtotal solo me aparece 120 ...
  #1 (permalink)  
Antiguo 31/03/2014, 14:35
 
Fecha de Ingreso: diciembre-2013
Mensajes: 81
Antigüedad: 10 años, 3 meses
Puntos: 1
numeros decimales

necesito realizar una suma de producto en la base de datos tengo el valor por ejemplo
120.000 y en el subtotal solo me aparece 120
les dejo el codigo para ver si me pueden ayudar

Código HTML:
<?php
//session_start(); original
if(isset($_GET['id']))
{
$_SESSION['carrito'][$_GET['id']]=$_GET['id'];
}
require 'conexion.php';
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Documento sin título</title>
</head>
<script>
function requerir(){
	try{
	req=new XMLHttpRequest();
	}catch(err1){
		try{
		req=new ActiveXObject("Microsoft.XMLHTTP");
		}catch(err2){
			try{
			req=new ActiveXObject("Msxml2.XMLHTTP");
			}catch(err3){
			req= false;
			}
		}
	}
return req;
}
function cantidad(id)
{
	//c1
	//alert(id.substr(1));
	var peti=requerir();
	var url="proceso.php";
	var valor=document.getElementById(id).value;
	if(valor<1 || valor=="")
		valor=1;
		
	var vari="valor="+valor+"&id="+id.substr(1);
	//alert(vari);
	peti.open("POST",url,true);
	peti.onreadystatechange = function(){
		if(peti.readyState==4)
		{
			if(peti.status==200)
			{
				//alert(peti.responseText);
				//location.reload();
				document.getElementById('s'+id.substr(1)).value=peti.responseText;
				total();
			
			}else{
				alert("Error --- "+peti.statusText);
			}
		}
	};
	peti.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
	peti.send(vari);

}
function total()
{
	var id = document.getElementById('tabla');
	var val = id.getElementsByTagName("input"); 
	var total=0;
		for(var i=0;i<val.length;++i)
		{
			
			if(i%2==1 ){
			total+=parseFloat(val[i].value);
			
			
			}
		}
		document.getElementById('total').value=Math.round(total*100)/100;
}
function solonumero(e) {
    tecla = (document.all) ? e.keyCode : e.which;
   // alert(tecla);
	if (tecla==8){ return true;} //Tecla de retroceso (para poder borrar)
    //if (tecla==44) return true; //Coma ( En este caso para diferenciar los decimales )
    else if (tecla==48) {return true}
    else if (tecla==49) {return true}
    else if (tecla==50) {return true}
    else if (tecla==51) {return true}
    else if (tecla==52) {return true}
    else if (tecla==53) {return true}
    else if (tecla==54) {return true}
    else if (tecla==55) {return true}
    else if (tecla==56) {return true}
	else if (tecla==57) {return true}
	else if (tecla==46) {return true}//punto 
	else{alert('Solo puede ingresar numeros en esta casilla');}
    patron = /1/; //ver nota
    te = String.fromCharCode(tecla);
    return patron.test(te); 
}
</script>
<body>
<p>
</p>
<table width="521" border="1" id="tabla">
    <tr>
      <td width="58" height="24" align="center" bgcolor="#999999">#n</td>
      <td width="172" align="center" bgcolor="#999999">producto</td>
      <td width="115" align="center" bgcolor="#999999">precio unit.</td>
      <td width="71" align="center" bgcolor="#999999">Subtotal</td>
      <td width="71" align="center" bgcolor="#999999">&nbsp;</td>
    </tr>
    <?php
  $cad="";
foreach($_SESSION['carrito'] as $k)
{
	$cad.=' or id='.$k;
}
$sql="select * from tb_producto where id=-1 ".$cad;

//echo $sql;
conectar();
$re=mysql_query($sql)or die (mysql_error());
desconectar();
$total=0;
$item="";
$cant=0;
$i=1;
while($f=mysql_fetch_array($re)){
?>
    <tr>
      <td><input name="c<?php echo $f['id'];?>" type="text" id="c<?php echo $f['id'];?>" 
    value="<?php if(isset($_SESSION['cantidad'][$f['id']])){
		$total+=$_SESSION['cantidad'][$f['id']]*$f['precio'];
		echo $_SESSION['cantidad'][$f['id']];
		$cant=$_SESSION['cantidad'][$f['id']];
		}else{
			$total+=$f['precio'];
			echo 1;
			$cant=1;
		}
		?>" size="3" onkeyup="cantidad(this.id)" onKeyPress="return solonumero(event)"></td>
      <td><?php echo $f['nombre'];?></td>
      <td><?php echo $f['precio'];?></td>
      <td align="center"><input name="s<?php echo $f['id'];?>" type="text" id="s<?php echo $f['id'];?>" 
    value="<?php if(isset($_SESSION['cantidad'][$f['id']])){
		echo $_SESSION['cantidad'][$f['id']]*$f['precio'];
		
		}else{
			echo $f['precio'];
		}
		?>" size="7" readonly></td>
      <td align="center"><a href="eliminar.php?id=<?php echo $f['id'];?>">Eliminar</a></td>
    </tr>
    <?php
	
	$item.='<input type="hidden" name="item_name_'.$i.'" value="'.$f['nombre'].'"> 
 <input type="hidden" name="amount_'.$i.'" value="'.$f['precio'].'"> 
 <input type="hidden" name="currency_code_'.$i.'" value="USD">
 <input type="hidden" name="quantity_'.$i.'" value="'.$cant.'">
 ';
 $i++;
 
}
?>
  </table>

<p>
  total
  <input name="total" type="text" id="total" 
  value="<?php echo $total;?>" readonly>
  
</p>
<p><div id="boton" >
<!-- cuando lo usen con una cuenta real de paypal cambiar 
https://www.sandbox.paypal.com/cgi-bin/webscr
por
https://www.paypal.com/cgi-bin/webscr

-->
<form action="https://www.paypal.com/cgi-bin/webscr" method="post" target="_blank">  
 <input type="hidden" name="cmd" value="_cart"> 
 <input type="hidden" name="upload" value="1"> 
 <input type="hidden" name="business" value="poner aqui tu correo de prueba o real"> 
 <?php  echo $item;?>
 <!--
 <input type="hidden" name="item_name_1" value="carrito"> 
 <input type="hidden" name="amount_1" value="1.00"> 
 
 si hubiuera precio de flete
 <input type="hidden" name="shipping_1" value="1.75"> 

 <input type="hidden" name="item_name_2" value="Item Name 2"> 
 <input type="hidden" name="amount_2" value="2.00"> 
 -->

 <input type="image" src="https://www.paypalobjects.com/es_ES/ES/i/btn/btn_buynowCC_LG.gif" border="0" name="submit" alt="PayPal. La forma r&aacute;pida y segura de pagar en Internet.">
 
</form>
</div></p>
<p><a href="producto.php">seguir comprando </a></p>
</body>
</html> 
Código PHP:
<?php
session_start
();
require 
'conexion.php';

$id=$_POST['id'];
conectar();
$re=mysql_query("select precio from tb_producto where id=".$id)or die(mysql_error());
desconectar();
$precio=mysql_result($re,0);
$valor=$_POST['valor'];
$_SESSION['cantidad'][$id]=$valor;
echo 
$valor $precio;
?>
  #2 (permalink)  
Antiguo 01/04/2014, 07:41
Colaborador
 
Fecha de Ingreso: septiembre-2013
Ubicación: España
Mensajes: 3.648
Antigüedad: 10 años, 7 meses
Puntos: 578
Respuesta: numeros decimales

Tiene que ser de tipo string, de otra forma se eliminan ceros después del punto.
  #3 (permalink)  
Antiguo 02/04/2014, 21:52
 
Fecha de Ingreso: diciembre-2013
Mensajes: 81
Antigüedad: 10 años, 3 meses
Puntos: 1
Respuesta: numeros decimales

si le pongo string me quedaran todos los cero??
  #4 (permalink)  
Antiguo 03/04/2014, 04:10
Avatar de IsaBelM
Colaborador
 
Fecha de Ingreso: junio-2008
Mensajes: 5.032
Antigüedad: 15 años, 10 meses
Puntos: 1012
Respuesta: numeros decimales

has de usar toFixed() y multiplicarlo por 1 de este modo el valor pasa a ser interge
Cita:
parseFloat(val[i].value).toFixed(2) *1
__________________
if(ViolenciaDeGénero) {alert('MUJER ASESINADA');}

Etiquetas: html, input, numeros, php, select, valor
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




La zona horaria es GMT -6. Ahora son las 10:37.