note 24379 modified in function.round by danbrown

From: Date: Sun, 17 May 2009 16:27:15 +0000
Subject: note 24379 modified in function.round by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-154829@lists.php.net to get a copy of this message
Here's a function to round to an arbitary number of significant digits. Don't confuse it with rounding to a negative precision - that counts back from the decimal point, this function counts forward from the Most Significant Digit. ex: <?php round(1241757, -3); // 1242000 RoundSigDigs(1241757, 3); // 1240000 ?> Works on negative numbers too. $sigdigs should be >= 0 <?php function RoundSigDigs($number, $sigdigs) { $multiplier = 1; while ($number < 0.1) { $number *= 10; $multiplier /= 10; } while ($number >= 1) { $number /= 10; $multiplier *= 10; } return round($number, $sigdigs) * $multiplier; } ?> --was-- Here's a function to round to an arbitary number of significant digits. Don't confuse it with rounding to a negative precision - that counts back from the decimal point, this function counts forward from the Most Significant Digit. ex: round(1241757, -3); // 1242000 RoundSigDigs(1241757, 3); // 1240000 Works on negative numbers too. $sigdigs should be >= 0 function RoundSigDigs($number, $sigdigs) { $multiplier = 1; while ($number < 0.1) { $number *= 10; $multiplier /= 10; } while ($number >= 1) { $number /= 10; $multiplier *= 10; } return round($number, $sigdigs) * $multiplier; } http://php.net/manual/en/function.round.php

« previous php.notes (#154829) next »