简体   繁体   中英

Strange behavior when dividing inputs

I am building a basic application to learn more, but have came across an issue.

I have 3 input boxes. people, bill, tip. the maths is as follows:

(bill + tip) / people. When i try to divide in my code it seems to add onto the end of my total.

So far i have this. http://jsfiddle.net/ma9ic/a8eJT/

    var updateTotal = function () {
      var people = parseInt($('#people').val());
      var bill = ($('#bill').val());
      var tip = ($('#tip').val());
      var billTip = bill + tip;
      var billTipPeople = billTip / people;




      $('#total').text("£" + billTipPeople) 

If i could get pointed in the right direction that would be great :)

You're pretty close. I got it working like this

var updateTotal = function () {
  var people = parseInt($('#people').val(),10);
  var bill = parseFloat($('#bill').val());
  var tip = parseFloat($('#tip').val());
  var billTip = bill + tip;
  var billTipPeople = billTip / people;
  if (isNaN(billTipPeople)) billTipPeople = 0; // output zero if NaN

  $('#total').text("£" + billTipPeople.toFixed(2)) 

The issue is that javascript has some weird rules about string concatenation. "1"+"1" == "11". You need to be explicit every time.

parseInt GOTCHA : ALWAYS use the second (optional) base parameter of parseInt. Values like "015" will be parsed as octal into the decimal number 13 otherwise. Hence the popular joke, "Why do programmers confuse Halloween and Christmas? Because OCT31 == DEC25!"

bill + tip will perform string concatenation, not addition, because they are both string. At least one of the operands has to be a number if you want to perform addition.

While parseFloat and parseInt work, using the unary plus operator is shorter to write and you don't have to worry about the type of number:

var people = +$('#people').val();
var bill = +$('#bill').val();
var tip = +$('#tip').val();

This works as long as the input value only consists of a number. But if the input only starts with a number, eg "5 foo" and you want to extract the number from the beginning of the string, you really have to use parseInt or parseFloat .

Your bill and tip variables are strings. Try using parseFloat() . Using the addition sign ( + ) on two strings will simply concatenate them.

var bill = parseFloat($('#bill').val());
var tip = parseFloat($('#tip').val());

While you used parseInt() in one case, why didn't you follow same path in similar situations?

Anyway, here's how I have modified your code:

$(document).ready(function () {

$('input#bill, input#tip').blur(function () {
    var num = parseFloat($(this).val());
    if (isNaN(num)) {
        return;
    }
    var cleanNum = num.toFixed(2);
    $(this).val(cleanNum);
    if (num / cleanNum < 1) {}
});

$('#people, #bill, #tip').keyup(function () {
    updateTotal();
});



var updateTotal = function () {
    var people = parseInt($('#people').val());
    if (isNaN(people) || people === 0) {
        return;
    }
    var bill = parseFloat($('#bill').val());
    if (isNaN(bill)) {
        bill = 0;
    }
    var tip = parseFloat($('#tip').val());
    if (isNaN(tip)) {
        tip = 0;
    }
    var billTip = bill + tip;
    var billTipPeople = billTip / people;

    $('#total').text("£" + billTipPeople);
    // round up to 2 d.p. like below:
    // $('#total').text("£" + billTipPeople.toFixed(2));
};

});

To save you from coming back again and asking why your app has decided to come up another crazy behaviour, I've added the following checks:

When user enters number of people, even though we are not ready to enter total cost of bill , it is updated as NaN. We prevent this nasty behaviour by...

if (isNaN(num)) {
    return;
}

We take same precaution in the updateTotal() function. Moreover, watch out for division by 0!* I give tips onle when I'm with my gf, otherwise, a person like me will break your app...

if (isNaN(people) || people === 0) {
    return;
}

Here's the fiddle >> http://jsfiddle.net/a8eJT/11/

尝试在javascript中使用parseInt()parseFloat() 。当您不使用它们时,它将被视为字符串。

try

var updateTotal = function () {
      var people = parseInt($('#people').val());
      var bill = parseInt($('#bill').val());
      var tip = parseInt($('#tip').val());
      var billTip = bill + tip;
      var billTipPeople = billTip / people;

      $('#total').text("£" + billTipPeople) 

I have added parseint to both bill & tip

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM