Programing

자바 스크립트에서 NaN을 0으로 변환

lottogame 2020. 5. 1. 08:00
반응형

자바 스크립트에서 NaN을 0으로 변환


if 문없이 NaN 값을 0으로 변환하는 방법이 있습니까?

if (isNaN(a)) a = 0;

매번 변수를 확인하는 것은 매우 성가신 일입니다.


당신은 이것을 할 수 있습니다 :

a = a || 0

...을 "falsey"값에서로 변환합니다 0.

"falsey"값은 다음과 같습니다.

  • false
  • null
  • undefined
  • 0
  • "" (빈 문자열)
  • NaN (숫자가 아님)

또는 원하는 경우 :

a = a ? a : 0;

... 위와 같은 효과가 있습니다.


의도가 just 이상을 테스트하려는 경우 NaN동일한 작업을 수행 할 수 있지만 toNumber 변환을 먼저 수행하십시오.

a = +a || 0

단항 + 연산자를 사용하여 a숫자 로 변환하려고합니다 . 이것은 숫자 문자열과 같은 것을 숫자로 변환하는 이점이 있습니다 '123'.

누군가 예기치 않은 숫자로 변환 할 수있는 Array를 전달하는 경우가 발생할 수 있습니다.

+['123']  // 123

여기에 숫자 문자열 인 단일 멤버가있는 Array가 있습니다. 숫자로 성공적으로 변환됩니다.


이중 물결표를 사용하면 (더블 비트 NOT)-- ~~JavaScript에서 흥미로운 작업을 수행합니다. 예를 들어, 대신 Math.floor또는 대신 사용할 수 있습니다 parseInt("123", 10)! 웹에서 많이 논의되었으므로 여기서 작동하는 이유는 다루지 않겠지 만 관심이 있으시다면 JavaScript의 "double tilde"(~~) 연산자는 무엇입니까?

우리는 이중 물결표 의이 속성 NaN을 사용하여 숫자 로 변환 할 수 있으며 행복하게도 그 숫자는 0입니다!

console.log(~~NaN); // 0


자신의 방법을 작성하고 숫자 값을 원하는 모든 곳에서 사용하십시오.

function getNum(val) {
   if (isNaN(val)) {
     return 0;
   }
   return val;
}

계속해서 사용할 수 있도록하기보다는 백업하지 말고 왜 처음에 NaN을 사용하는지 궁금하십니까?

연산에 대한 숫자 입력이 NaN 인 경우 출력도 NaN이됩니다. 이것이 현재 IEEE 부동 소수점 표준이 작동하는 방식입니다 (Javascript만이 아닙니다). 그 행동은 좋은 이유입니다 . 근본적인 의도는 가짜를 깨닫지 않고 가짜 결과를 사용하지 못하게하는 것입니다.

NaN이 작동하는 방식은 하위 하위 작업 (하위 수준에서 NaN 생성)에서 문제가 발생하는 경우 최종 결과 NaN이되어 NaN이됩니다. 오류 처리 로직 (throw / catch 어쩌면?)이 아직 완료되지 않았습니다.

NaN as the result of an arithmetic calculation always indicates something has gone awry in the details of the arithmetic. It's a way for the computer to say "debugging needed here". Rather than finding some way to continue anyway with some number that's hardly ever right (is 0 really what you want?), why not find the problem and fix it.

A common problem in Javascript is that both parseInt(...) and parseFloat(...) will return NaN if given a nonsensical argument (null, '', etc). Fix the issue at the lowest level possible rather than at a higher level. Then the result of the overall calculation has a good chance of making sense, and you're not substituting some magic number (0 or 1 or whatever) for the result of the entire calculation. (The trick of (parseInt(foo.value) || 0) works only for sums, not products - for products you want the default value to be 1 rather than 0, but not if the specified value really is 0.)

Perhaps for ease of coding you want a function to retrieve a value from the user, clean it up, and provide a default value if necessary, like this:

function getFoobarFromUser(elementid) {
        var foobar = parseFloat(document.getElementById(elementid).innerHTML)
        if (isNaN(foobar)) foobar = 3.21;       // default value
        return(foobar.toFixed(2));
}

How about a regex?

function getNum(str) {
  return /[-+]?[0-9]*\.?[0-9]+/.test(str)?parseFloat(str):0;
}

The code below will ignore NaN to allow a calculation of properly entered numbers

function getNum(str) {
  return /[-+]?[0-9]*\.?[0-9]+/.test(str)?parseFloat(str):0;
}
var inputsArray = document.getElementsByTagName('input');

function computeTotal() {
  var tot = 0;
  tot += getNum(inputsArray[0].value);
  tot += getNum(inputsArray[1].value);
  tot += getNum(inputsArray[2].value);
  inputsArray[3].value = tot;
}
<input type="text"></input>
<input type="text"></input>
<input type="text"></input>
<input type="text" disabled></input>
<button type="button" onclick="computeTotal()">Calculate</button>


var i = [NaN, 1,2,3];

var j = i.map(i =>{ return isNaN(i) ? 0 : i});

console.log(j)

[0,1,2,3]


Something simpler and effective for anything :

function getNum(val) {
   val = +val || 0
   return val;
}

...which will convert a from any "falsey" value to 0.

The "falsey" values are:

  • false
  • null
  • undefined
  • 0
  • "" ( empty string )
  • NaN ( Not a Number )

using user 113716 solution, which by the way is great to avoid all those if-else I have implemented it this way to calculate my subtotal textbox from textbox unit and textbox quantity.

In the process writing of non numbers in unit and quantity textboxes, their values are bing replace by zero so final posting of user data has no non-numbers .

     <script src="/common/tools/jquery-1.10.2.js"></script>
     <script src="/common/tools/jquery-ui.js"></script>

     <!----------------- link above 2 lines to your jquery files ------>





    <script type="text/javascript" >
    function calculate_subtotal(){

    $('#quantity').val((+$('#quantity').val() || 0));
    $('#unit').val((+$('#unit').val() || 0));

    var  calculated = $('#quantity').val() * $('#unit').val() ;
    $('#subtotal').val(calculated);


    }
    </script>


      <input type = "text" onChange ="calculate_subtotal();" id = "quantity"/>
      <input type = "text" onChange ="calculate_subtotal();" id = "unit"/>
      <input type = "text" id = "subtotal"/>

Please try this simple function

var NanValue = function (entry) {
    if(entry=="NaN") {
        return 0.00;
    } else {
        return entry;
    }
}

참고URL : https://stackoverflow.com/questions/7540397/convert-nan-to-0-in-javascript

반응형