Skip navigation

Monthly Archives: August 2015


It is common in forms, to get user inputs for numerical calculations later like house rent allowance for salary calculation. In such scenarios, the value returned is string which if we add result in concatenation. To avoid this mistake adding toInt method to string object directly will be handy.

/**
 * adding toInt method to String object
 * author rajakvk <rajakvk at gmail dot com>
 */
if(!String.toInt) {
  /**
   * Returns integer value if a string value is passed.
   * @name toInt
   * @methodOf String
   * @param {*} none 
   * @returns {Number}
   */
  String.prototype.toInt = function() {
     return parseInt(this, 10);
  }
}
// Usage
// $('#hra').val().toInt();
// typeof $('#hra').val();  // string
// typeof $('#hra').val().toInt();  // number

Note: This method converts string to Integer discarding decimal places.

Advertisements