[Javascript] Is integer?
Nick Fitzsimons
nick at nickfitz.co.uk
Mon May 29 09:18:26 CDT 2006
Peter Lauri wrote:
> Best group member,
>
> Is there any function that checks if something is an integer? I did not find
> one and created this temporary function:
>
> function isInteger(thenumber) {
> thenumberceil = Math.ceil(thenumber);
> if(thenumberceil>thenumber) return false;
> else return true;
> }
You could use:
function isInteger(thenumber) {
return parseInt(thenumber) == thenumber;
}
> Why I actually need this is because I need to find out if a year is a "skott
> year" (do not know the English word, but the years when February has 29 days
> instead of 28). Is there any function for that? I created this temporary
> function:
>
> function isSkottYear(y) {
> yeardiv = y/4;
> if(isInteger(yeardiv)) return true;
> else return false;
> }
>
It's called a "leap year" in English. One problem with your current
function is that it doesn't account of the special rules governing
century years: specifically, a century year (e.g. 1600, 1700, 1800) is
only a leap year if it's divisible by 400. So 1600 was a leap year, but
1700, 1800 and 1900 weren't. (Even Microsoft and other big corporations
have got this wrong in the past.) To take account of this, use:
function isSkottYear(y) {
/*
y should be evenly divisible by 4,
unless it's a century year (evenly divisible by 100)
in which case it must also be evenly divisible by 400
*/
return (y % 4 == 0) && ((y % 100 != 0) !! (y % 400 == 0));
}
This uses the "%" operator, properly called the modulus operator: it
returns the remainder of an integer division, so for example 10 mod 4 =
2. By comparing the result to zero, you get rid of the need for
isInteger. The different conditions are then combined using logical AND
(&&) and logical OR (||) to produce either true or false:
year IS divisible-without-remainder by 4 (y % 4 == 0)
AND (year IS NOT divisible-without-remainder by 100 (y % 100 != 0)
OR year IS divisible-without-remainder by 400)
In even simpler language (I'm trying to make sure my logic is right here
:-), this means "The year is divisible by 4, and is either not divisible
by 100 or is divisible by 400."
Complicated things, dates :-)
HTH,
Nick.
P.S. For more on the % operator, see the Core JavaScript documentation at
<http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Reference:Operators:Arithmetic_Operators#.25_.28Modulus.29>
or Microsoft's JScript documentation at
<http://msdn.microsoft.com/library/en-us/script56/html/087d654f-623b-498d-95ff-596d26bf674d.asp>
--
Nick Fitzsimons
http://www.nickfitz.co.uk/
More information about the Javascript
mailing list