Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 3 of 3
  1. #1
    Regular Coder
    Join Date
    Jul 2002
    Location
    USA
    Posts
    151
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Number.toLongString() method for extremely large values

    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.
    Code:
    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;
    }
    Last edited by Algorithm; 02-01-2003 at 08:25 PM.

  • #2
    Moderator
    Join Date
    May 2002
    Location
    Hayward, CA
    Posts
    1,459
    Thanks
    1
    Thanked 23 Times in 21 Posts
    You'll get a JavaScript strict warning from that in Mozilla browsers.

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

    I'd suggest:

    Code:
    Number.prototype.toLongString = function(){
      if (arguments.length > 0) {
        var radix = arguments[0];
      } else {
        radix = 10;
      }
    // ...
    "The first step to confirming there is a bug in someone else's work is confirming there are no bugs in your own."
    June 30, 2001
    author, Verbosio prototype XML Editor
    author, JavaScript Developer's Dictionary
    https://alexvincent.us/blog

  • #3
    Regular Coder
    Join Date
    Jul 2002
    Location
    USA
    Posts
    151
    Thanks
    0
    Thanked 0 Times in 0 Posts
    Good point. The necessary changes have been made.


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •