note 95485 deleted from function.round by googleguy

From: Date: Sun, 09 Dec 2012 08:20:57 +0000
Subject: note 95485 deleted from function.round by googleguy
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-192413@lists.php.net to get a copy of this message
Note Submitter: edgarmveiga at gmail dot com ---- Trying to simulate the toPrecison function of Javascript, I have obtained this method. Any sugestions or revisions [sent to me by email, not posted here] would be appreciated: <?php /** * Rounding to significant digits ( just like JS toPrecision() ) * * @number <float> value to round * @sf <int> Number of significant figures */ public function toPrecision($number, $sf) { // How many decimal places do we round and format to? // @note May be negative. $dp = floor($sf - log10(abs($number))); // Round as a regular number. $numberFinal = round($number, $dp); //If the original number it's halp up rounded, don't need the last 0 $arrDecimais=explode('.',$numberFinal); if(strlen($number) > strlen($numberFinal) && $dp > strlen($arrDecimais[1])) { $valorFinal=sprintf("%.".($dp-1)."f", $number); } else { //Leave the formatting to format_number(), but always format 0 to 0dp. $valorFinal=str_replace(',', '', number_format($numberFinal, 0 == $numberFinal ? 0 : $dp)); } // Verify if needs to be represented in scientific notation $arrDecimaisOriginal=explode('.',$number); if(sizeof($arrDecimaisOriginal)>=2) { return (strlen($arrDecimaisOriginal[0])>$sf)? sprintf("%.".($sf-1)."E", $valorFinal) : $valorFinal; } else { return sprintf("%.".($sf-1)."E", $valorFinal); } } ?>

« previous php.notes (#192413) next »