Page 1 of 1

Math function problem

Posted: Thu Apr 15, 2004 10:02 pm
by S_henry
I want to display 12345.6789 as 1.23456789e+4. Anybody knows what function in PHP I should use?

Posted: Thu Apr 15, 2004 10:06 pm
by John Cartwright
I'm not sure how to do scientific notation but I'm sure it's easily found on google.

Posted: Thu Apr 15, 2004 11:38 pm
by S_henry
Anybody has any idea pls? I just try to find it but it's really very hard to found in the internet (maybe for me).

Posted: Fri Apr 16, 2004 12:02 am
by Pyrite
I'm sure you can write a function based on the algorithm.

a.) Move the decimal point to the right of the first nonzero digit. Count the number of places you moved the decimal point.

b.) Multiply the number from step a.) times 10 raised to + or - the number of places you moved the decimal point.
Use + if you moved the decimal to the left.
Use - if you moved the decimal to the right.

Code: Select all

function sci($x, $d=-1) {
   $min=($x<0)?"-":"";
   $x=abs($x); 
   $e=floor(($x!=0)?log10($x):0);
   $x*=pow(10,-$e);
   $fmt=($d>=0)?".".$d:"";
   $e=($e>=0)?"+".sprintf("%02d",$e):"-".sprintf("%02d",-$e);
   return sprintf("$min%".$fmt."fe%s",$x,$e);
&#125;

Posted: Mon Apr 19, 2004 2:58 am
by S_henry
Thanx. Your function is really great.

Posted: Mon Apr 19, 2004 7:58 am
by feyd

Code: Select all

sprintf("%.9e",1234.56789);
prints 1.23456789e+3
works in 4.3.4 at least...

edit: slight tweak to the format...

Posted: Wed Apr 21, 2004 10:12 pm
by Pyrite
feyd wrote:

Code: Select all

sprintf("%.9e",1234.56789);
prints 1.23456789e+3
That doesn't print anything for me ..

Posted: Wed Apr 21, 2004 10:19 pm
by Illusionist
same here... You sure that works feyd??

Posted: Wed Apr 21, 2004 10:21 pm
by Illusionist
feyd wrote:

Code: Select all

sprintf("%.9e",1234.56789);
prints 1.23456789e+3
works in 4.3.4 at least...

edit: slight tweak to the format...
If your slight tweak was changing printf to sprintf, then you shouldn't have done that. It is wrong. Take the 's' off and it'll work fine.

Posted: Thu Apr 22, 2004 1:21 am
by Chris Corbyn
Pyrite, how the hell did you pluck that code out of the air. It looks totally crazy.

Well done all the same 8)

Posted: Thu Apr 22, 2004 2:22 am
by feyd
php.net ;)