How to NOT leave the javascript convert my number to exponential notation?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Felipe Oliveira Gutierrez
    New Member
    • Sep 2010
    • 1

    How to NOT leave the javascript convert my number to exponential notation?

    I hava a number too large and when i plus it with another number the result is showed in exponential notation on my screen.

    how to not leave the javascript do that?

    Thanks
  • mrhoo
    Contributor
    • Jun 2006
    • 428

    #2
    You are probably better off with the exponential notation.

    Javascript loses precision after 15 or so digits.

    928447654652812 3456781 may be rounded to
    928447654652812 4000000, and

    0.0000000000928 447654652812345 6781 to
    0.0000000000928 4476546528124

    If you need more precision you can use a javascript big integer library,
    or hand off the calculations to a library on the server.

    If you just want to replace the notation with the rounded number,
    you can do it with a replace operation on the string value of the number.

    Numbers smaller than zero will be returned with the zeroes in front of the first significant digit,
    big numbers will add zeroes to the end.


    Code:
    Number.prototype.todigits= function(){
    	var tem='', z, d, s= this.toString(),
    	x= s.match(/^(\d+)\.(\d+)[eE]([-+]?)(\d+)$/);
    	if(x){
    		d= x[2];
    		z= (x[3]== '-')? x[4]-1: x[4]-d.length;
    		while(z--)tem+='0';
    		if(x[3]== '-'){
    			return '0.'+tem+x[1]+d;
    		}
    		return x[1]+d+tem;
    	}
    	return s;
    }

    Code:
    //TEST
    var n= 0.00000000009284476546528123456781,
    n2= 9284476546528123456781;
    alert(n+'\n'+n.todigits()+'\n'+ n2+'\n'+n2.todigits())
    
    returned value: (String):
    9.284476546528124e-11
    0.00000000009284476546528124
    9.284476546528124e+21
    9284476546528124000000
    Last edited by Dormilich; Sep 14 '10, 06:37 PM. Reason: spelling

    Comment

    • Dormilich
      Recognized Expert Expert
      • Aug 2008
      • 8694

      #3
      Javascript loses precision after 15 or so digits.
      all IEEE 754 floats do that. (that is the only number type in JavaScript)

      Comment

      Working...