note 7951 modified in function.printf by felipe

From: Date: Mon, 21 Jul 2008 01:12:15 +0000
Subject: note 7951 modified in function.printf by felipe
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-142377@lists.php.net to get a copy of this message
There are times when you don't want a number like .0002 to be truncated to .00 - where you'd like to actually have at least some number of significant digits, not just the decimal places. Here's a sample of how you might do that, although scientific notation might be better. Why doesn't PHP support some of the other C style floating point formats? <?php // string FloatFormat(float $Value, int $Precision) // - AGS 21/08/2000 // //There is no range checking performed here so the // function will vaporize on out of range values. function FloatFormat($Value, $Precision) { $decimals = log10(abs($Value)); $decimals = - (intval(min($decimals, 0)) - $Precision); $format = "%." . $decimals . "f"; return sprintf($format, $Value); } ?> --was-- There are times when you don't want a number like .0002 to be truncated to .00 - where you'd like to actually have at least some number of significant digits, not just the decimal places. Here's a sample of how you might do that, although scientific notation might be better. Why doesn't PHP support some of the other C style floating point formats? // string FloatFormat(float $Value, int $Precision) // - AGS 21/08/2000 // //There is no range checking performed here so the // function will vaporize on out of range values. function FloatFormat($Value, $Precision) { $decimals = log10(abs($Value)); $decimals = - (intval(min($decimals, 0)) - $Precision); $format = "%." . $decimals . "f"; return sprintf($format, $Value); } http://php.net/manual/en/function.printf.php

« previous php.notes (#142377) next »