1

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?

Thanks

3 Answers3

1

Use Math.round:

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;
Peter van der Wal
  • 11,141
  • 2
  • 21
  • 29
1

You could modify your code to,

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

You can also use the toFixed method for rounding to specific decimal points as follows,

Example

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
melc
  • 11,523
  • 3
  • 36
  • 41
0

you can add a round method

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

and use it like this

var total = round(val1 + val2);

and then pass total to your final statement.

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

As for how to actually round, you can look at this.

Community
  • 1
  • 1
hvgotcodes
  • 118,147
  • 33
  • 203
  • 236