【问题标题】:calculating percent in javascript [duplicate]在javascript中计算百分比[重复]
【发布时间】:2020-12-30 01:00:47
【问题描述】:

我正在尝试将乘法结果相加,但我想要的结果不匹配,你能帮我看看我的 javascript 代码中的错误在哪里吗?

我想要的结果: ((x*10)/100)+x = ... 或 ((30.000 * 10) / 100)+30.000 = 33000

但为什么我得到的结果 = 300030000

var x = document.getElementById("x");
var y = document.getElementById("y");
var d = document.getElementById("d");
var xstored = x.getAttribute("data-in");
var ystored = y.getAttribute("data-in");
setInterval(function(){
    if( x == document.activeElement ){
     var temp = x.value;
     if( xstored != temp ){
       xstored = temp;
       x.setAttribute("data-in",temp);
       calculate();
     }
    }
    if( y == document.activeElement ){
     var temp = y.value;
     if( ystored != temp ){
       ystored = temp;
       y.setAttribute("data-in",temp);
       calculate();
     }
    }
},50);

function calculate(){
 d.innerHTML = ((x.value * y.value) / 100) + x.value ;
}
x.onblur = calculate;
calculate();
<div class="section">
    <div class="container">
        <h3>Calculate</h3>
        <input id="x" data-in="" type="text" />
        x <input id="y" data-in="" type="text" />
        <hr>
        <div id="d"></div>
    </div>
</div>

【问题讨论】:

  • var temp = parseInt(x.value); 解决了吗?你的问题似乎是两个字符串被连接
  • 将您的输入值转换为整数 - 默认情况下它们被解释为字符串,因此 + 运算符将它们连接起来。

标签: javascript calculation


【解决方案1】:

input元素的值是一个字符串,所以在相加之前需要将其转换为数字,以防止它被视为字符串连接。这可以使用unary plus operator 来完成。

d.innerHTML = ((x.value * y.value) / 100) + (+x.value);

【讨论】:

    猜你喜欢
    • 2019-04-03
    • 1970-01-01
    • 1970-01-01
    • 2015-09-04
    • 2013-05-05
    • 2017-02-08
    • 2012-09-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多