Site logo

Functions for Number

Add leading zeroes before number

function pad000(myNumber) {
return ('000'+myNumber).match (/...$/)[0];
} alert(ZeroPad(123, 10)); function ZeroPad(num, digit) { var tmp = num.toString(); while (tmp.length < digit) { tmp = "0" + tmp; } return tmp; }

Another 'leading zeroes' function:

function lz (number, len) {
	if (String (number).length >= len)
		return number;
	var leading_zeroes = '';
	for (var i = 0; i < len - String (number).length; i++)
		leading_zeroes += '0';
	return leading_zeroes + number;
}

$.writeln(lz (123, 5));

Pad a number with leading zeros

function pad(number, length, fill) {
    if (fill == undefined) fill = "0";
    var str = '' + number;
    while (str.length < length) {
        str = fill + str;
    }
    return str;
}

Round number by Marc Autret

var number = 12.248481545454;
alert(roundToDP (number ,2))
 
function roundToDP (val,dig)
{
     // Including all its zeros, lopping off beyond:
     val = Math.round(val*Math.pow(10,dig));
     // Force in decimal point at the right place:
     val = String(val);
   //  return val.slice(0,val.length-dig)+"."+val.slice(dig);
     return val.slice(0,val.length-dig)+"."+val.slice(val.length-dig);
}


var number = Math.round(12.248481545454*100)/100;

var number = RoundWithDecimal(12.248481545454,2);
 
function RoundWithDecimal(number,decimals){
    var multiplier = Math.pow(10,decimals);
    return Math.round(number*multiplier)/multiplier;
}

Round string

function RoundString(numVal, decimals) {
    var retVal = Math.round(numVal * Math.pow(10,decimals)) + "";
    retVal = retVal.substring(0,retVal.length-decimals) + "." + retVal.substring(retVal.length-decimals);
    return retVal;
}

Romanize-deromanize functions

Is a number even?

function IsEven(number) {
	return (number % 2 == 0) ? true : false;
}

See also UnitValue

Convert Fahrenheit to Celsius and vice versa

main();

function main() {
	alert(fToC(45), "Fahrenheit to Celsius");
	alert(cToF(60), "Celsius to Fahrenheit");
}

function cToF(celsius) {
	var cTemp = celsius;
	var cToFahr = cTemp * 9 / 5 + 32;
	var result = cTemp+'\xB0C is ' + cToFahr + ' \xB0F.';
	return result;
}

function fToC(fahrenheit) {
	var fTemp = fahrenheit;
	var fToCel = (fTemp - 32) * 5 / 9;
	var result = fTemp+'\xB0F is ' + fToCel + '\xB0C.';
	return result;
}

Approximately equals

main();

function main() {
	var value1 = 30;
	var value2 = 32.0;
	var acceptableDifference = 3;
	var approximatelyEquals = ApproximatelyEquals(value1, value2, acceptableDifference);
}

function ApproximatelyEquals(value1, value2, acceptableDifference) {
	return Math.abs(value1 - value2) <= acceptableDifference; 
}

Random number function

alert(randomNumber(1000));

function randomNumber(limit) {
	return Math.floor(Math.random()*limit);
}

Tips

Here + is just a fancy way of casting str to number

var str = "123";
var num = +str;