简体   繁体   English

划分输入时的奇怪行为

[英]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. 我有3个输入框。 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/ 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. 问题是javascript有一些关于字符串连接的怪异规则。 "1"+"1" == "11". “ 1” +“ 1” ==“ 11”。 You need to be explicit every time. 您每次都必须明确。

parseInt GOTCHA : ALWAYS use the second (optional) base parameter of parseInt. parseInt GOTCHA :始终使用parseInt的第二个(可选) 基本参数。 Values like "015" will be parsed as octal into the decimal number 13 otherwise. 否则,将像“ 015”之类的值八进制解析为十进制数字13。 Hence the popular joke, "Why do programmers confuse Halloween and Christmas? Because OCT31 == DEC25!" 因此,流行的笑话是“为什么程序员会混淆万圣节和圣诞节?因为OCT31 == DEC25!”

bill + tip will perform string concatenation, not addition, because they are both string. bill + tip将执行字符串连接,而不是加法,因为它们都是字符串。 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: 虽然parseFloatparseInt工作,但是使用一元加号运算符的编写时间较短,并且您不必担心数字的类型:

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 . 但是,如果输入仅以数字开头 ,例如"5 foo"并且您想从字符串的开头提取数字,则实际上必须使用parseIntparseFloat

Your bill and tip variables are strings. 您的话小费变量是字符串。 Try using parseFloat() . 尝试使用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? 在一种情况下使用parseInt()时,为什么在相似情况下不遵循相同的路径?

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. 当用户输入人数时,即使我们还没有准备输入账单的总费用 ,它也会被更新为NaN。 We prevent this nasty behaviour by... 我们通过...防止这种令人讨厌的行为

if (isNaN(num)) {
    return;
}

We take same precaution in the updateTotal() function. 我们在updateTotal()函数中采取相同的预防措施。 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... 此外,请注意除以0!*当我与我的gf在一起时,我只会提供提示,否则,像我这样的人会破坏您的应用程序...

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

Here's the fiddle >> http://jsfiddle.net/a8eJT/11/ 这是小提琴 >> 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 我已将parseint添加到billtip

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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