Redondeo de cifras al más cercano

I was looking for the answer to round after a calculation but I cannot seem to find it. I know you have to use the round code in your javascript but I do not know where to put it, it does not seem to work..

      val1 = parseInt($("#figure1").val());
      val2 = parseInt($("#figure2").val());
      $("#totalcost").val( ("$" val1 + val2 ));

Where would I put the rounding code, so it rounds the total cost?

Muchas Gracias

preguntado el 02 de diciembre de 13 a las 19:12

3 Respuestas

Utilice la herramienta Ronda de matemáticas:

var rounded = Math.round(val1 + val2);
$("#totalcost").val("$" + rounded);

Or, when you want to round it on 2 decimals

var rounded = Math.round((val1 + val2) * 100) / 100;

Respondido el 02 de diciembre de 13 a las 19:12

You could modify your code to,

var val1 = parseFloat($("#figure1").val());
var val2 = parseFloat($("#figure2").val());
$("#totalcost").val( ("$" + Math.round(val1 + val2) ));

También puedes utilizar la toFixed method for rounding to specific decimal points as follows,

Ejemplo

var val1 = parseFloat(1.12521);
var val2 = parseFloat(2.3213123);
var total= ("$" + Math.round(val1 + val2) );
var totalWithTwoDecimals= ("$" + (val1 + val2).toFixed(2) );
console.log(total);//$3
console.log(totalWithTwoDecimals);//$3.45

Respondido el 02 de diciembre de 13 a las 19:12

puedes agregar un round Método

function round(valToRound) {
// do the rounding
}

y úsalo así

var total = round(val1 + val2);

y luego pasar total to your final statement.

$("#totalcost").val("$"+ total);

As for how to actually round, you can mira este.

contestado el 23 de mayo de 17 a las 11:05

Math with a capital M? - codigoshvgot

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.