macintosh264 macintosh264 - 2 years ago 112
PHP Question

Advanced Php Number Formatting

I want to have a PHP number formatted with a minimum of 2 decimal places and a maximum of 8 decimal places. How can you do that properly.

Update: I'm sorry, my question is say I have number "4". I wish for it to display as "4.00" and if I have "2.000000001" then it displays as "2.00" or if I have "3.2102" it will display as such. There is a NSNumber formatter on iPhone, what is the equivalent in PHP.

Answer Source

This formats the $n number for 8 decimals, then removes the trailing zero, max 6 times.

$s = number_format($n, 8);
for($i=0; $i<8-2; $i++) {
    if (substr($s, -1) == '0')
        $s = substr($s, 0, -1);
print "Number = $s";
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download