note 95485 modified in function.round by danbrown

From: Date: Tue, 18 Jan 2011 14:34:10 +0000
Subject: note 95485 modified in function.round by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-175862@lists.php.net to get a copy of this message
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); } } ?> --was-- Trying to simulate the toPrecison function of Javascript, I have obtained this method. Any sugestions or revisions 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); } } ?> http://php.net/manual/en/function.round.php

« previous php.notes (#175862) next »