我有两个字符串,其中只包含数字:
var num1 = '20',
num2 = '30.5';
我本以为我可以把它们加在一起,但它们却被连接起来:
num1 + num2; // = '2030.5'
我如何才能迫使这些字符串被视为数字?
我有两个字符串,其中只包含数字:
var num1 = '20',
num2 = '30.5';
我本以为我可以把它们加在一起,但它们却被连接起来:
num1 + num2; // = '2030.5'
我如何才能迫使这些字符串被视为数字?
当前回答
如果您正在寻找简单的Javascript代码,并希望使用两个输入框并从两个值中添加数字,请尝试此方法。这是代码。
Enter the first number: <input type="text" id="num1" /><br />
Enter the seccond number: <input type="text" id="num2" /><br />
<input type="button" onclick="call()" value="Add"/>
<script type="text/javascript">
function call(){
var q=parseInt(document.getElementById("num1").value);
var w=parseInt(document.getElementById("num2").value);
var result=q+w;
}
</script>
欲了解更多详情,请访问http://informativejavascript.blogspot.nl/2012/12/javascript-basics.html
其他回答
我建议使用一元加运算符,强制将最终字符串作为数字处理,在圆括号内,使代码更具可读性,如下所示:
(+varname)
所以,在你的例子中是:
var num1 = '20',
num2 = '30.5';
var sum = (+num1) + (+num2);
// Just to test it
console.log( sum ); // 50.5
在这里,你有两个选择:-
1.您可以使用一元加号将字符串数字转换为整数。 2.您还可以通过将数字解析为相应的类型来实现这一点。即parseInt(), parseFloat()等
.
现在我将在这里通过例子向你们展示(求两个数字的和)。
使用一元加运算符
<!DOCTYPE html>
<html>
<body>
<H1>Program for sum of two numbers.</H1>
<p id="myId"></p>
<script>
var x = prompt("Please enter the first number.");//prompt will always return string value
var y = prompt("Please enter the second nubmer.");
var z = +x + +y;
document.getElementById("myId").innerHTML ="Sum of "+x+" and "+y+" is "+z;
</script>
</body>
</html>
〇使用解析方法
<!DOCTYPE html>
<html>
<body>
<H1>Program for sum of two numbers.</H1>
<p id="myId"></p>
<script>
var x = prompt("Please enter the first number.");
var y = prompt("Please enter the second number.");
var z = parseInt(x) + parseInt(y);
document.getElementById("myId").innerHTML ="Sum of "+x+" and "+y+" is "+z;
</script>
</body>
</html>
使用parseFloat(string)将字符串转换为浮点数或使用parseInt(string)将字符串转换为整数
如果你想将数字作为字符串来执行操作(就像在数字大于64位的情况下),你可以使用大整数库。
const bigInt = require('big-integer')
bigInt("999").add("1").toString() // output: "1000"
可以使用parseInt将字符串解析为数字。为了安全起见,始终传递10作为以10为基数解析的第二个参数。
num1 = parseInt(num1, 10);
num2 = parseInt(num2, 10);
alert(num1 + num2);