user3247231
user3247231

Reputation: 1

Rounding Decimals

Trying to teach myself something and could only get half way. I have some code doing some math for my but it is throwing the wrong answer because I can't get it to round to 2 decimal places. I was hoping someone could help.

Example: Put 34 in the "sec" input and the "decimal" would read .57

Here is the link on Fiddle. http://jsfiddle.net/dgtlkvn/mHsgt/

And here is the javascript as I know it is where the problem is.

$(document).ready (
function() {
  $('#min').keyup(calculate);
  $('#sec').keyup(calculate);
  $('#dec').keyup(calculate);
  $('#dis').keyup(calculate);
  $('#kilo').keyup(calculate);
  $('#speed').keyup(calculate);

});

function calculate(e) {
  $('#dec').val($('#sec').val() / 60);
  $('#dis').val($('#min').val() + $('#dec').val());
  $('#kilo').val(60 / $('#dis').val());
}

Upvotes: 0

Views: 112

Answers (2)

RobG
RobG

Reputation: 147493

The value of form controls are always returned as strings. Most arithmetic operations will convert them to numbers but not + which will do concatenation if any argument is a string, so

 $('#dis').val($('#min').val() + $('#dec').val());

does concatenation, not addition.

To round numbers to a fixed number of places, use toFixed. Sample code (I think it's simpler and much more efficient to ditch jQuery for this):

function calculate(evt) {
  var el = evt.target || evt.srcElement;
  var f = el.form;

  if (!f) return;

  // Division converts strings to numbers
  var dec = f.sec.value / 60;

  // Use unary + to convert strings to numbers for addition
  var dis = +f.min.value + +f.dec.value;

  // Dispaly values to 2 decimal places (or round if preferred)
  f.dec.value = dec.toFixed(2);
  f.dis.value = dis.toFixed(2);
  f.kilo.value = (60 / dis).toFixed(2);
}

Some HTML:

<form id="f0" onkeyup="calculate(event);">
  <table>
    <tr><td>Min:<td><input type="text" name="min">
    <tr><td>Sec:<td><input type="text" name="sec">
    <tr><td>Dec:<td><input type="text" name="dec">
    <tr><td>Dis:<td><input type="text" name="dis">
    <tr><td>Km:<td><input type="text" name="kilo">
    <tr><td>Speed:<td><input type="text" name="speed">
  </table>
</form>

Upvotes: 1

Gowri
Gowri

Reputation: 1856

Try this

$('#dec').val(Math.floor(($('#sec').val() / 60) * 100) / 100);

http://jsfiddle.net/mHsgt/1/

Upvotes: 0

Related Questions