-1

I had to use this to get the integer value of a field:

var local = {};
local.result = $('#myID').val();
local.result = parseInt(0 + local.result);
return local.result;

Q: Is there a best practice instead, like some sort of jQuery method that returns a value or the number 0 if it's not a value?

I gotta have more jQuery!

Phillip Senn
  • 43,069
  • 83
  • 242
  • 359

3 Answers3

2

Your code will fail dismally in some browsers, as they will see the number starting with 0 as being base-8. Try this instead:

return parseInt(document.getElementById('myID').value,10) || 0;
Niet the Dark Absol
  • 301,028
  • 70
  • 427
  • 540
  • 1
    Note that in [ES5](http://www.ecma-international.org/ecma-262/5.1/#sec-15.1.2.2): "The specification of the function parseInt no longer allows implementations to treat Strings beginning with a 0 character as octal values." But they do. – RobG Mar 21 '13 at 01:10
0

You can just use +val to attempt to coerce any string str to a number.

If you have possible non-numeric values, and want to default to 0, as in your original post:

var num = +str || 0;

JSFiddle: http://jsfiddle.net/F8wWN/2/

Related JS ninja tricks: What does = +_ mean in JavaScript

I'm not sure if you are implying any float conversion. It seems it's already an integer because otherwise you wouldn't be able to parseInt on it, right?

Community
  • 1
  • 1
Andrew Mao
  • 31,800
  • 17
  • 126
  • 212
0

"Best practice" is relative: what is best for someone else may not be best for you.

If you want to check if the value is a positive integer, then a regular expression may fit the bill:

var intRe = /^\d+$/;
var el = document.getElementById('id');
el.value = intRe.test(el.value)? el.value || 0;

if you want to test for negative integers, modify the regular expression to allow an optional leading minus sign (-):

var intRe = /^\-?d+$/;

You may want to trim leading and trailing white space for convenience. Note that 2.343e3 is a valid positive integer.

RobG
  • 124,520
  • 28
  • 153
  • 188