Math function problem
Moderator: General Moderators
Math function problem
I want to display 12345.6789 as 1.23456789e+4. Anybody knows what function in PHP I should use?
- John Cartwright
- Site Admin
- Posts: 11470
- Joined: Tue Dec 23, 2003 2:10 am
- Location: Toronto
- Contact:
- Pyrite
- Forum Regular
- Posts: 769
- Joined: Tue Sep 23, 2003 11:07 pm
- Location: The Republic of Texas
- Contact:
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.
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);
}- feyd
- Neighborhood Spidermoddy
- Posts: 31559
- Joined: Mon Mar 29, 2004 3:24 pm
- Location: Bothell, Washington, USA
Code: Select all
sprintf("%.9e",1234.56789);
prints 1.23456789e+3edit: slight tweak to the format...
- Pyrite
- Forum Regular
- Posts: 769
- Joined: Tue Sep 23, 2003 11:07 pm
- Location: The Republic of Texas
- Contact:
That doesn't print anything for me ..feyd wrote:Code: Select all
sprintf("%.9e",1234.56789); prints 1.23456789e+3
-
Illusionist
- Forum Regular
- Posts: 903
- Joined: Mon Jan 12, 2004 9:32 pm
-
Illusionist
- Forum Regular
- Posts: 903
- Joined: Mon Jan 12, 2004 9:32 pm
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.feyd wrote:works in 4.3.4 at least...Code: Select all
sprintf("%.9e",1234.56789); prints 1.23456789e+3
edit: slight tweak to the format...
- Chris Corbyn
- Breakbeat Nuttzer
- Posts: 13098
- Joined: Wed Mar 24, 2004 7:57 am
- Location: Melbourne, Australia