Test if number is odd or even

You were right in thinking mod was a good place to start. Here is an expression which will return true if $number is even, false if odd: $number % 2 == 0 Works for every integerPHP value, see as well Arithmetic OperatorsPHP. Example: $number = 20; if ($number % 2 == 0) { print “It’s … Read more

Allow 2 decimal places in

Instead of step=”any”, which allows for any number of decimal places, use step=”.01″, which allows up to two decimal places. More details in the spec: https://www.w3.org/TR/html/sec-forms.html#the-step-attribute

How can I set max-length in an HTML5 “input type=number” element?

And you can add a max attribute that will specify the highest possible number that you may insert <input type=”number” max=”999″ /> if you add both a max and a min value you can specify the range of allowed values: <input type=”number” min=”1″ max=”999″ /> The above will still not stop a user from manually … Read more

How to format a floating number to fixed width in Python

numbers = [23.23, 0.1233, 1.0, 4.223, 9887.2] for x in numbers: print(“{:10.4f}”.format(x)) prints 23.2300 0.1233 1.0000 4.2230 9887.2000 The format specifier inside the curly braces follows the Python format string syntax. Specifically, in this case, it consists of the following parts: The empty string before the colon means “take the next provided argument to format()” … Read more

How do I convert an integer to binary in JavaScript?

function dec2bin(dec) { return (dec >>> 0).toString(2); } console.log(dec2bin(1)); // 1 console.log(dec2bin(-1)); // 11111111111111111111111111111111 console.log(dec2bin(256)); // 100000000 console.log(dec2bin(-256)); // 11111111111111111111111100000000 You can use Number.toString(2) function, but it has some problems when representing negative numbers. For example, (-1).toString(2) output is “-1”. To fix this issue, you can use the unsigned right shift bitwise operator (>>>) to … Read more