Skip navigation

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

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: