Nodejs String to Number Convert toNumber()

Here you can find the source of toNumber()

Method Source Code

/**//from   w  w w .  j av  a 2  s.co 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);
   }
};

Related

  1. toNum()
    String.prototype.toNum = function() {
       if (this.length === 0) return 0;
       return parseInt(this);
    
  2. toNumber()
    String.prototype.toNumber = function() {
        return parseInt(this);
    };
    var ten = "10";
    var fifty = "50";
    console.log(ten.toNumber()); 
    console.log(fifty.toNumber()); 
    
  3. toNumber()
    String.prototype.toNumber = function() {
      return parseFloat(this);
    };
    
  4. toNumber()
    String.prototype.toNumber = function(){
      return +this;
    };
    
  5. toNumber()
    String.prototype.toNumber = function(){
      var str = this.gsub(",", ".");
      if (str.length == 0)
        return 0;
      var parts = str.split(".");
      if (parts.length > 1){               
        var res = '';
        for(var i=0; i<parts.length-1; i++){
          res = res + parts[i];
    ...
    
  6. toNumber()
    String.prototype.toNumber = function() {
        return Number(this);
    
  7. toNumber()
    String.prototype.toNumber = function()
      var res = 0;
      for(var i = this.length - 1; i >= 0; --i) {
        res += res * 256 + this.charCodeAt( i );
      return res;