답변:
단항 더하기 연산자를 사용하여 먼저 숫자로 변환합니다.
+num1 + +num2;
parseInt에서는 기수가 10으로 지정되어 기본 10에 있습니다. 엄격하지 않은 자바 스크립트에서 앞에 붙는 숫자 0는 8 진수로 처리됩니다. 이것은 분명히 문제를 일으킬 것입니다!
parseInt(num1, 10) + parseInt(num2, 10) //base10
parseFloat(num1) + parseFloat(num2)
단항 연산자를 사용하는 유용한 바로 가기는 ChaosPandion의 답변을 참조하십시오 . 다른 행동을 보여주기 위해 바이올린을 설정했습니다.
var ten = '10';
var zero_ten = '010';
var one = '1';
var body = document.getElementsByTagName('body')[0];
Append(parseInt(ten) + parseInt(one));
Append(parseInt(zero_ten) + parseInt(one));
Append(+ten + +one);
Append(+zero_ten + +one);
function Append(text) {
body.appendChild(document.createTextNode(text));
body.appendChild(document.createElement('br'));
}
+num1 + +num2더 짧고, 아마도 더 우아합니다. 기본적으로 단항 +연산자는 다음과 같이 변환됩니다.Number
단항 더하기 연산자를 사용하여 코드를 다음과 같이 더 읽기 쉽도록 괄호 안에 숫자로 취급하도록 강제하는 것이 좋습니다.
(+varname)
따라서 귀하의 경우 :
var num1 = '20',
num2 = '30.5';
var sum = (+num1) + (+num2);
// Just to test it
console.log( sum ); // 50.5
var result = Number(num1) + Number(num2);
로 문자열을 변환 floats과 parseFloat(string)나에게 integers로parseInt(string)
parseInt(string, 10) 참조하십시오.
매우 큰 숫자 인 두 개의 문자열을 함께 추가해야하는 경우 모든 문자열 위치에서 추가를 평가해야합니다.
function addStrings(str1, str2){
str1a = str1.split('').reverse();
str2a = str2.split('').reverse();
let output = '';
let longer = Math.max(str1.length, str2.length);
let carry = false;
for (let i = 0; i < longer; i++) {
let result
if (str1a[i] && str2a[i]) {
result = parseInt(str1a[i]) + parseInt(str2a[i]);
} else if (str1a[i] && !str2a[i]) {
result = parseInt(str1a[i]);
} else if (!str1a[i] && str2a[i]) {
result = parseInt(str2a[i]);
}
if (carry) {
result += 1;
carry = false;
}
if(result >= 10) {
carry = true;
output += result.toString()[1];
}else {
output += result.toString();
}
}
output = output.split('').reverse().join('');
if(carry) {
output = '1' + output;
}
return output;
}
시험
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 라는 책을 집어들 수 있습니다 . 자바 스크립트는 꽤 큰 규모의 문제를 안고 있습니다! 이 책은 그것들을 명확히하는 데 먼 길을 갔다. 또한보십시오
그리고 Crockford 씨의 훌륭한 에세이, Javascript : 세계에서 가장 오해 된 프로그래밍 언어 .
숫자를 문자열로 사용하여 작업을 수행하려는 경우 (숫자가 64 비트보다 클 수있는 경우와 같이) 큰 정수 라이브러리를 사용할 수 있습니다 .
const bigInt = require('big-integer')
bigInt("999").add("1").toString() // output: "1000"
여기에는 두 가지 옵션이 있습니다.
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>
자바 스크립트가 버그이기 때문에 최종 답변을 소수점 이하 16 자리 미만으로 반올림하십시오.
예를 들어 5-7.6 = -2.5999999999999996
@ cr05s19xx는 중복 질문에 제안했습니다.
자바 스크립트는 숫자와 덧셈에있어 약간 재미 있습니다.
다음을주는
'20'- '30'= 10; // 10을 숫자 '20'+ '30'= '2030'으로 반환합니다. // 문자열로 반환합니다. document.getElementById에서 반환 된 값은 문자열이므로 더하기 또는 빼기를 진행하기 전에 모두 (작동하는 값도 포함)를 숫자로 파싱하는 것이 좋습니다. 코드는 다음과 같습니다.
function myFunction() {
var per = parseInt(document.getElementById('input1').value);
var num = parseInt(document.getElementById('input2').value);
var sum = (num / 100) * per;
var output = num - sum;
console.log(output);
document.getElementById('demo').innerHTML = output;
}
function myFunction2() {
var per = parseInt(document.getElementById('input3').value);
var num = parseInt(document.getElementById('input4').value);
var sum = (num / 100) * per;
var output = sum + num;
console.log(output);
document.getElementById('demo1').innerHTML = output;
}
내 프로젝트에서 이것을 사용합니다. + 부호를 사용하여 문자열을 숫자로 취급합니다 (with_interesst 변수에서)
<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>
그것이 도움이되기를 바랍니다.
간단한 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을 방문하십시오.