두 문자열을 숫자처럼 추가하는 방법은 무엇입니까?


176

숫자 만 포함하는 두 개의 문자열이 있습니다.

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

나는 그것들을 함께 추가 할 수있을 것으로 기대했지만 대신 연결되어 있습니다.

num1 + num2; // = '2030.5'

이 문자열을 숫자로 취급하도록하려면 어떻게해야합니까?

답변:


378

단항 더하기 연산자를 사용하여 먼저 숫자로 변환합니다.

+num1 + +num2;

9
매우 시원합니다. 이것을 공유해 주셔서 감사합니다. 단항 더하기 연산자와 다른 데이터 유형에 미치는 유용한 영향을 설명하는이 기사를 찾았습니다. xkr.us/articles/javascript/unary-add
mrtsherman

4
그러나이 수가 2 ^ 53보다 크면 문자열의 일부를 추가하고 캐리지를 루프의 각 파트로 전달하는 함수를 작성해야합니다. : D
trusktr

2
이로 인해 오류가 발생하여 대신 parseFloat ()를 사용했습니다.
Hawkee

1
아래 @NicholasCarey 답변 참조 : stackoverflow.com/a/8976770/1579667
Benj

이것을 수행하는 덜 해킹 된 방법이 있습니까? (면책 조항 : 이것이 내가 항상해온 방법입니다.)
seebiscuit

20

구문 분석 용 MDN 문서 구문 분석 용
MDN 문서

parseInt에서는 기수가 10으로 지정되어 기본 10에 있습니다. 엄격하지 않은 자바 스크립트에서 앞에 붙는 숫자 0는 8 진수로 처리됩니다. 이것은 분명히 문제를 일으킬 것입니다!

parseInt(num1, 10) + parseInt(num2, 10) //base10
parseFloat(num1) + parseFloat(num2)

단항 연산자를 사용하는 유용한 바로 가기는 ChaosPandion의 답변을 참조하십시오 . 다른 행동을 보여주기 위해 바이올린을 설정했습니다.

http://jsfiddle.net/EtX6G/

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'));
}

2
소수점이 있으면 parseFloat ()를 사용하십시오. :)
Diodeus-James MacFarlane

1
또한 기수를 10으로 지정해야합니다.
ChaosPandion

그리고 +num1 + +num2더 짧고, 아마도 더 우아합니다. 기본적으로 단항 +연산자는 다음과 같이 변환됩니다.Number
Raynos

구문 분석 할 때 소수점 이하 자릿수를 잃지 않습니까?
DOK

그만한 가치가있는 parseInt 및 parseFloat는 실험적이며 브라우저에서 광범위하게 지원되지 않으며 모바일에서는 거의 지원되지 않습니다.

14

단항 더하기 연산자를 사용하여 코드를 다음과 같이 더 읽기 쉽도록 괄호 안에 숫자로 취급하도록 강제하는 것이 좋습니다.

(+varname)

따라서 귀하의 경우 :

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

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

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



6

매우 큰 숫자 인 두 개의 문자열을 함께 추가해야하는 경우 모든 문자열 위치에서 추가를 평가해야합니다.

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;
}

5

이것을 사용하여 숫자를 추가 할 수 있습니다.

var x = +num1 + +num2;

4

시험

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 : 세계에서 가장 오해 된 프로그래밍 언어 .


3

나는 항상 제로를 뺀 것입니다.

num1-0 + num2-0;

단항 연산자 방법은 하나의 문자가 적지 만 모든 사람이 단항 연산자가 무엇인지 또는 그것이 무엇인지 모르는 경우에 구글을 찾는 방법을 아는 것은 아닙니다.


2

숫자를 문자열로 사용하여 작업을 수행하려는 경우 (숫자가 64 비트보다 클 수있는 경우와 같이) 큰 정수 라이브러리를 사용할 수 있습니다 .

const bigInt = require('big-integer')
bigInt("999").add("1").toString() // output: "1000"

2

여기에는 두 가지 옵션이 있습니다.

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>

2
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 ;
}

1

parseInt문자열을 숫자로 구문 분석하는 데 사용할 수 있습니다 . 사물의 안전을 위해 항상 1010 진법으로 구문 분석 할 두 번째 주장으로 전달 하십시오.

num1 = parseInt(num1, 10);
num2 = parseInt(num2, 10);
alert(num1 + num2);

1

자바 스크립트가 버그이기 때문에 최종 답변을 소수점 이하 16 자리 미만으로 반올림하십시오.

예를 들어 5-7.6 = -2.5999999999999996


1
JavaScript는 버그가 없으며 다른 모든 것과 동일한 IEEE754 부동 소수점을 사용합니다. 언급 한 부정확성은 사용자가 지정하고 10 진수로 표시하는 숫자에 이진 부동 소수점 산술을 사용한 결과입니다.
Michael Geary

1

@ 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;
}

0

parseFloat방법을 사용하여 문자열을 부동 소수점 숫자로 구문 분석하십시오.

parseFloat(num1) + parseFloat(num2)

0

내 프로젝트에서 이것을 사용합니다. + 부호를 사용하여 문자열을 숫자로 취급합니다 (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>

그것이 도움이되기를 바랍니다.


0
document.getElementById(currentInputChoosen).value -= +-100;

나와 같은 문제가 발생하여 해당 사례에 대한 해결책을 찾지 못하고이 SO 질문을 찾으면 제 경우에는 효과가 있습니다.

약간의 주제를 벗어난 것은 유감이지만, 이것이 방금 작동한다는 것을 알았을 때 공유 가치가 있다고 생각했습니다.

더러운 해결 방법인지 실제로 합법적인지 알 수 없습니다.


-1

다음과 같이 사용할 수 있습니다.

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

alert((num1*1) + (num2*1)); //result 50.5

num1에 * 1을 적용하면 문자열을 숫자로 변환하십시오.

num1에 문자 나 쉼표가 있으면 NaN에 1을 곱한 값을 반환합니다.

num1이 널인 경우 num1은 0을 리턴합니다.

친절한 안부 !!!


-2

간단한 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을 방문하십시오.

당사 사이트를 사용함과 동시에 당사의 쿠키 정책개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.