Tuesday, 31 August 2010

valueToInt(value, up) JavaScript

/**
 * Function which accepts two parameters.
 * @param value - value passed into the function either a float, int or string (containing a number).
 * @param up - boolean value which defines whether returned integer should be rounded rounded up or rounded down
 * 
 * If "up" isn't present then the number is rounded, if "up" is true then the number is rounded up 
 * else it's rounded down.
 */
function valueToInt(value, up){
  var returnValue;
  // From: http://joeyjavas.com/2007/06/25/javascript-how-to-remove-all-commas-from-a-number/
  // If we have a number that's in the format 123,456.00 this removes the commas and gives us 123456.00 
  // which can subsequently be parsed as a float.
  if(typeof(value) == "string"){
    value = value.replace(/\,/g,'');
    try{
      returnValue = parseFloat(value)
    }catch(e){
      returnValue = 0;
    }
  }
  if(typeof(value) == "number"){
    returnValue = parseFloat(returnValue)
  }
  if(!up){
    returnValue = parseInt(Math.round(returnValue));
  }else{
    if(typeof(up) == "boolean"){
      if(up){
        returnValue = parseInt(Math.ceil(value));
      }else{
        returnValue = parseInt(Math.floor(value));
      }
    }else{
      returnValue = parseInt(Math.round(returnValue));
    }
  }
  return returnValue;
}

And to add them back:

function commaFormat(amount){
  var number = '' + amount;

  if (number.length > 3) {
    var mod = number.length % 3;

    var output = (mod > 0 ? (number.substring(0,mod)) : '');

    for (i=0 ; i < Math.floor(number.length / 3); i++) {

      if ((mod == 0) && (i == 0)){

        output += number.substring(mod+ 3 * i, mod + 3 * i + 3);

      }else{
        output+= ',' + number.substring(mod + 3 * i, mod + 3 * i + 3);

      }
    }
    return (output);
  }

  else return number;
}

As per CodeColorizer or here.

No comments:

Post a Comment