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; }

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;
}

Roman Numeral Converter

Romanize

function Romanize(num) {
  var lookup = {M:1000,CM:900,D:500,CD:400,C:100,XC:90,L:50,XL:40,X:10,IX:9,V:5,IV:4,I:1},
      roman = '',
      i;
  for ( i in lookup ) {
    while ( num >= lookup[i] ) {
      roman += i;
      num -= lookup[i];
    }
  }
  return roman;
}

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;
}