[turboid] javascript solutions

Home     Contact     Search     About me
Numbers
07 Mar 2012

New math and time functions for JavaScript

Including an easy-to-use stop watch

The standard math and time functions of JavaScript are widely sufficient. Anyhow, Turboid provides useful math and time functions which make a developer's life little easier. In this article you find a bunch of such functions and its descriptions.
The standard math and time functions of JavaScript are widely sufficient. Anyhow, Turboid provides useful math and time functions which make a developers life little easier. In this article you find a bunch of such functions and its descriptions.

For example, one misses in standard JavaScript handy solutions for a number of requisites which occur quite often, like easily generating an random number greater than 1 and at the same time not greater then a certain maximum; or counting the digits of a number; or extracting a number of a string like "50px"...

So here you have a list of Turboid arithmetic and time-related functions:


randomTo(max)

Returns a random number which is greater than or equal to zero and at the same time smaller than or equal to max.


getDigits(numVal)

Returns an array of the digits of numVal.


countDigits(numVal)

Returns the number of digits in numVal.


round(value [, numOfDigits])

Rounds a number value like Math.round(), but allows delimiting the number of positions after the decimal point (numOfDigits, optional).


numIn(str)

A very important function for extracting numbers in strings containing letters and other characters. Example: numIn("width:50px") returns 50 (as a number, not a string).


makeEven(num)

Makes an odd number even by reducing it to the next lower even integer number if necessary. Alternative notation: _(num).makeEven()


isOdd(n)

Returns whether number n is odd or not. Alternative notation: _(num).isOdd()


isInt(n)

Returns whether number n is an integer number or not. Alternative notation: _(num).isInt()


forceDigits(val, num)

Forces a number to have a certain amount of digits by putting additional zeros at the beginning. Returns a string. For example, forceDigits(568, 5) returns "00568".


ignoreLeadingZeros(numAsStr)

Converts for example "00568" to 568. Returns a number, not a string. This is an alternative to numIn() and standard JavaScript parseInt, which unfortunately both return 0 in such cases.


new Clock()

Generates a stop watch. Provides two object functions, .start(), which starts the timer, and .stop(), which returns the measured time. Usage example:

var watch = new Clock();
watch.start();

alert("Do you want to see how long you have waited?");

alert("You have waited "+watch.stop()+" milliseconds");


Comments

Add comment:

Name: (required)
E-Mail: (required, remains invisible)
Website:
Comment:
Please check all (anti-spam):