Ernesto
Ernesto

Reputation: 4017

Override Javascript's toString for numbers

I'm overriding the toString method for numbers in javascript, because I need it to return "" for NaN values, instead of the default "NaN":

Number.prototype.original_toString = Number.prototype.toString;
Number.prototype.toString = function(radix) {
  var originalValue = this.original_toString(radix);
  if (originalValue == "NaN") {
    return "";
  } else {
    return originalValue;
  }
};

Then I get the following behavior:

(3).toString()         => "3"
Number.NaN.toString()  => ""

That's ok. The problem is when I convert numbers to string the following way:

"" + 3            => "3"
"" + Number.NaN   => "NaN"  # This is not what I expected

As you can see, in this case the overridden method is not being used. Is there any other way to do this so that it works fine in both cases? I also tried overriding Number.prototype.toLocaleString and no luck. Here's a jsfiddle to play around with: http://jsfiddle.net/tmjf8cao/3/

Upvotes: 1

Views: 1700

Answers (2)

tugend
tugend

Reputation: 153

I think maybe the implicit toString method can't be overridden at all.

I.e.

Number.prototype.toString = function() { return "hello world!" };

(3).toString()  => "hello world!"
3 + "" => "3"

Upvotes: 1

Steve
Steve

Reputation: 11963

The problem is that, Num.NAN is a static variable(not a "number" belongs to number), which means you havent override its toString() method. You can try to override Number.NaN.toString also.

Upvotes: 2

Related Questions