Javascript String toNumber()

Description

Javascript String toNumber()


String.prototype.toNumber = function() {
    return parseInt(this);
};
var ten = "10";
var fifty = "50";
console.log(ten.toNumber()); //10
console.log(fifty.toNumber()); //50

Javascript String toNumber()

String.prototype.toNumber = function() {
    return parseInt(this, 10);
};

Javascript String toNumber()

String.prototype.toNumber = function() {
  return parseFloat(this);
};

Javascript String toNumber()

/**//from w w w  . j a  v  a 2s. c  o m
@Name: String.prototype.toNumber
@Author: Paul Visco
@Version: 1.0 11/19/07
@Description: Converts a numeric string into an integer or float
@Return: Float If the original value has a decimal in it, a float is returned
@Return: Number If the original value is an interger, an integer value is returned
@Example:
var myString = '12';
var num = myString.toNumber() +2;
//num = 14 //without running toNumber it would return '122'

var myString = '12.4';
var num = myString.toNumber() +2;
//num = 14.4 //without running toNumber it would return '12.42'
*/
String.prototype.toNumber = function(){
 if(this.match(/\./)){
  return parseFloat(this, 10);
 } else {
  return parseInt(this, 10);
 }
};

Javascript String toNumber()

String.prototype.toNumber = function(){
 var str = this.gsub(",", ".");
 if (str.length == 0)
  return 0;/*from   w  w w  . j  ava  2 s. c  o  m*/
 var parts = str.split(".");
 if (parts.length > 1){               
  var res = '';
  for(var i=0; i<parts.length-1; i++){
   res = res + parts[i];
  }                  
  return parseFloat(res + '.' + parts[parts.length - 1]);
 }  
 else
  return parseFloat(parts[0]); 
}



PreviousNext

Related