...

View Full Version : Number.toLongString() method for extremely large values



Algorithm
02-01-2003, 07:49 AM
Update 02-01-03: Changed as per recommendations.

The standard Number.toString() method returns values in scientific notation once they exceed 10^20. In many cases, this is not an expected or desired result.

The toLongString() method provides a solution by always returning a literal numeric value regardless of the number's size. However, the value returned will not be accurate beyond the first [log base (radix) of (10^15)] digits.

radix: Optional. A number between 2 and 36, inclusive.
Number.prototype.toLongString = function(){
var radix, n = this, d, t = '', p = '';
if(arguments.length>0 && typeof(arguments[0])=='number'){
radix = Math.round(arguments[0]);
if(radix<2) radix = 2;
if(radix>36) radix = 36;
} else {
radix = 10;
}
if(n < 0){
n *= -1;
p = '-';
}
while(n > radix){
d = n % radix;
n = (n-d)/radix;
t = d.toString(radix) + t;
}
return p + n.toString(radix) + t;
}

Alex Vincent
02-01-2003, 07:05 PM
You'll get a JavaScript strict warning from that in Mozilla browsers.

http://www.javascriptkit.com/javatutors/serror.shtml

I'd suggest:



Number.prototype.toLongString = function(){
if (arguments.length > 0) {
var radix = arguments[0];
} else {
radix = 10;
}
// ...

Algorithm
02-01-2003, 08:26 PM
Good point. The necessary changes have been made.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum