【问题标题】:Javascript: How do I get the sum without concatantion?Javascript:如何在没有连接的情况下获得总和?
【发布时间】:2014-04-17 12:45:26
【问题描述】:

如何阻止 javascript 连接我试图获得总和的两个值。

我进行了搜索,发现 parseInt(String s) 将字符串转换为 int。但是当我尝试下面的尝试时失败了。

尝试过,但失败了。

$total = "£" + ( parseInt($amount2) +  parseInt($rent));

乱码

            $total = "£" + ($amount2 + $rent);

功能齐全

 function update(slider, val) {
            //changed. Now, directly take value from ui.value. if not set (initial, will use current value.)
            var $amount = slider == 1 ? val : $("#amount").val();
            var $duration = slider == 2 ? val : $("#duration").val();
            var $rent = $("#MonthlyRent").val();
            var $amount2 = $amount.replace('%', '');

            /* commented
            $amount = $( "#slider" ).slider( "value" );
            $duration = $( "#slider2" ).slider( "value" );
             */
            $total = "£" + ($amount2 + $rent);
            $("#amount").val($amount);
            $("#amount-label").text($amount);
            $("#duration").val($duration);
            $("#duration-label").text($duration);
            $("#total").val($total);
            $("#total-label").text($total);

            $('#slider a').html('<label><span class="glyphicon glyphicon-chevron-left"></span> ' + $amount + ' <span class="glyphicon glyphicon-chevron-right"></span></label>');
            $('#slider2 a').html('<label><span class="glyphicon glyphicon-chevron-left"></span> ' + $duration + ' <span class="glyphicon glyphicon-chevron-right"></span></label>');
        }

【问题讨论】:

  • 对于您的标题,它是 javascript,而不是 java ...
  • 考虑到它的数量,我建议改用parseFloat()
  • 请定义“失败”。会发生什么,您希望发生什么?
  • 这里捕获$amount2后的值是多少$amount.replace('%', '');

标签: javascript html asp.net .net


【解决方案1】:

您可以使用 Number() 对数字求和;

    $1="0.56";
    $2="0.65";
    var a=Number($1)+Number($2);
    alert("$"+a); 

Example jsFiddle

【讨论】:

    【解决方案2】:

    也许你可以尝试以下方法:

    $total = parseInt($amount2) +  parseInt($rent);
    $total = "£" + $total;
    

    【讨论】:

      【解决方案3】:

      假设$amount2 和$rent 持有数字:-

      $total = "£" + ($amount2 - - $rent);
      

      - - 是 string to integer converter 的简写形式,以后还会添加。

      对于以后的计算,使用isNaN 确保结果是一个数字。

      例子:

      if(!isNaN($total)){
          // do other calculations
      }
      else{
          // show error message or do nothing
      }
      

      【讨论】:

        猜你喜欢
        • 2013-01-15
        • 1970-01-01
        • 1970-01-01
        • 2019-09-22
        • 2021-02-09
        • 1970-01-01
        • 1970-01-01
        • 2012-01-17
        • 2023-03-12
        相关资源
        最近更新 更多