我有两个字符串,其中只包含数字:

var num1 = '20',
    num2 = '30.5';

我本以为我可以把它们加在一起,但它们却被连接起来:

num1 + num2; // = '2030.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>

其他回答

function sum(){
    var x,y,z;
    x = Number(document.getElementById("input1").value);
    y = Number(document.getElementById("input2").value);
    z = x + y;
    document.getElementById("result").innerHTML = z ;
}

我在我的项目中使用了这个。我使用+符号处理字符串作为一个数字(在with_interest变量)

<script>
function computeLoan(){
var amount = document.getElementById('amount').value;
var interest_rate = document.getElementById('interest_rate').value;
var days = document.getElementById('days').value;
var interest = (amount * (interest_rate * .01)) / days;
var payment = ((amount / days) + interest).toFixed(2);
var with_interest = (amount * (interest_rate * .01));
var with_interesst = (+amount * (interest_rate * .01)) + (+amount);
payment = payment.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
document.getElementById('payment').innerHTML = "Target Daily = PHP"+payment;
document.getElementById('with_interesst').innerHTML = "Amount w/Interest =   PHP"+with_interesst;
}
</script>

<div name="printchatbox" id="printchatbox">
 <form id="Calculate" class="form-horizontal">
   <h2>You Can Use This Calculator Before Submit </h2>
   <p>Loan Amount: PHP<input id="amount" type="number" min="1" max="1000000"  onchange="computeLoan()"></p>
   <p>Interest Rate: <input id="interest_rate" type="number" min="0" max="100" value="10" step=".1" onchange="computeLoan()">%</p>
    <p>Term<select id="days" type="number" min="1" max="72" step=".1" onchange="computeLoan()">
    <option value="40">40 Days</option>
    <option value="50">50 Days</option>
    <option value="60">60 Days</option>
    <option value="70">70 Days</option>
    <option value="80">80 Days</option>
    <option value="90">90 Days</option>
    <option value="100">100 Days</option>
    <option value="120">120 Days</option>
    </select>
    </p>                        
   <h2 id="payment"></h2>
   <h2 id ="with_interesst"></h2>
 </form>
</div>

希望能有所帮助

我建议使用一元加运算符,强制将最终字符串作为数字处理,在圆括号内,使代码更具可读性,如下所示:

(+varname)

所以,在你的例子中是:

var num1 = '20',
    num2 = '30.5';

var sum = (+num1) + (+num2);

// Just to test it
console.log( sum ); // 50.5

try

var x = parseFloat(num1) + parseFloat(num2) ;

或者,根据你的需要:

var x = parseInt(num1) + parseInt(num2) ;

http://www.javascripter.net/faq/convert2.htm

你可能想读一下Douglas Crockford写的《Javascript: the Good Parts》这本书。Javascript有一个相当大的陷阱集合!这本书对澄清这些问题大有帮助。另请参阅

http://www.crockford.com/ http://javascript.crockford.com/

以及Crockford先生的优秀文章《Javascript:世界上最被误解的编程语言》。

我总是减去0。

num1-0 + num2-0;

假定一元操作符方法少了一个字符,但并不是每个人都知道一元操作符是什么,或者当他们不知道它被称为什么的时候如何谷歌来找出它。