本文介绍了Javascript函数添加两个数字不能正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在html中的代码需要输入用户输入的数字,然后进行计算,然后显示输出。用户选择的输入被放入一个公式中,并且公式的结果被添加到用户输入号码中,但是当它将两个号码相加时,它会添加一个小数点。例如,如果选择数字11,则Rchange的结果是0.22,因此.22然后将11添加到11.22以获得newResistance,而不是将其显示为110.22。

 函数calc(表单){
if(isNaN(form.resistance.value)){
alert(Error in input);
返回false;

if(form.resistance.value.length> 32){
alert(Error in input);
返回false;
}
var Rchange = .01 * 2 * form.resistance.value;
var newResistance =(form.resistance.value + Rchange);
document.getElementById(newResistance)。innerHTML = chopTo4(newResistance);
}

函数chopTo4(raw){
strRaw = raw.toString(); $ str
if(strRaw.length - strRaw.indexOf(0)> 4)strRaw = strRaw.substring(0,strRaw.indexOf(0)+ 5);
返回strRaw;
}


解决方案

字符串。您需要将它们转换为您用途中的数字。



parseInt(form.resistance.value);
parseFloat(form.resistance.value);
+ form.resistance.value;
(三者中的任何一个都可以工作;我更喜欢前两个(除非你正在寻找一个浮点数,否则使用parseInt))

My code in html takes a user input number in and it does a calculation and then displays the output. The user chosen input is put into a formula and the result of the formula is added to the user input number but when it adds the two number together its adding a decimal spot. For example if the number 11 is chosen, the result of Rchange is 0.22, so .22 is then added 11 to be 11.22 for newResistance but instead it is displaying the value as 110.22 instead.

function calc(form) {
    if (isNaN(form.resistance.value)) {
        alert("Error in input");
        return false;
    }
    if (form.resistance.value.length > 32) {
        alert("Error in input");
        return false;
    }
    var Rchange = .01 * 2 * form.resistance.value;
    var newResistance = (form.resistance.value + Rchange);
    document.getElementById("newResistance").innerHTML = chopTo4(newResistance);
}

function chopTo4(raw) {
    strRaw = raw.toString();
    if (strRaw.length - strRaw.indexOf("0") > 4) strRaw = strRaw.substring(0, strRaw.indexOf("0") + 5);
    return strRaw;
}
解决方案

HTML DOM element properties are always strings. You need to convert them to numbers in your useage.

parseInt(form.resistance.value);parseFloat(form.resistance.value);+form.resistance.value;(Any of the three will work; I prefer the first two (use parseInt unless you're looking for a float))

这篇关于Javascript函数添加两个数字不能正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-27 16:46