JavaScript函数加两个数字不起作用

编程入门 行业动态 更新时间:2024-10-11 03:19:39
本文介绍了JavaScript函数加两个数字不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我的HTML代码使用一个用户输入数字,然后进行计算,然后显示输出.用户选择的输入被放到公式中,公式的结果被添加到用户输入数字中,但是当将两个数字相加时,将添加一个小数点.

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 it's adding a decimal spot.

例如,如果选择数字11,则Rchange的结果为0.22,因此对于newResistance,将.22加11到11.22,但是将其显示为110.22.

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元素属性始终是字符串.您需要在使用时将其转换为数字.

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

parseInt(form.resistance.value); parseFloat(form.resistance.value); +form.resistance.value;

(三个中的任何一个都可以;我更喜欢前两个(除非您要查找浮点数,否则请使用parseInt).)

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

更多推荐

JavaScript函数加两个数字不起作用

本文发布于:2023-11-30 07:54:21,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1649253.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:函数   不起作用   两个   数字   JavaScript

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!