note 45739 deleted from function.number-format by tomsommer
| From: | tomsommer@php.net | Date: | Thu, 16 Sep 2004 22:15:20 +0000 |
| Subject: | note 45739 deleted from function.number-format by tomsommer | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-76854@lists.php.net to get a copy of this message | ||
Note Submitter: marco dot m at tirol dot com
----
// If one tries to output a bulk of (floatingpoint) numbers row by row
// keeping the decimalpoint on the same position (as seen in Excel or any
// other spreadsheet) one can use this very very straightforward
// hence very simple piece of code to get the job done:
// (Perhaps some php guru out there is motivated to
// crunch and optimize it all into one line? ;) )
function decimaltabstop($number,$length,$decimals) {
$filltemp="_"; // temporary fill character
$fillreplace="*"; // fill character to be returned
// (one could prefer " "
$decimalsign="."; // full stoop or comma, it's up to you ;)
$formatted=round($number,$decimals);
$pos=strpos($formatted,$decimalsign);
if (!$pos===false) {
// format floating point numbers
$needtofill=abs(strlen($formatted)-$pos-$decimals-1);
if ($needtofill)
$formatted=$formatted.str_repeat($filltemp,$needtofill);
}
else {
// format integer numbers
$formatted=$formatted.str_repeat($filltemp,$decimals+1);
}
// fill up with leading fill character to desired length
$count=strlen($formatted);
$fuellen=str_repeat($filltemp,$length-$count);
$formatted=$fuellen.$formatted;
return (str_replace($filltemp,$fillreplace,$formatted));
} // function
//--------------------------------------------------
// inputs:
$value1=1123;
$value2=0.23;
$value3=11.1;
$value4=12000;
$value5=3.141592;
// Calling the function for several values within a table,
// we would like to see a string of 10 character in total
// including 4 decimals: (Note: The alignment of
// the cell is right orientated.)
echo "<TABLE><TR>";
echo "<TD align=right><font face=courier>";
echo decimaltabstop($value1,10,4);
echo "<BR>";
echo decimaltabstop($value2,10,4);
echo "<BR>";
echo decimaltabstop($value3,10,4);
echo "<BR>";
echo decimaltabstop($value4,10,4);
echo "<BR>";
echo decimaltabstop($value5,10,4);
echo "<BR>";
echo "</TD></TR></TABLE>";
// output:
// (using
// PHP 4.3.4 on WinXP running Apache 1.3.29
// and
// PHP 4.1.2 on Linux 2.4.25 running Apache 1.3.26)
//
// +------------+
// | *1123*****|
// | ****0.23**|
// | ***11.1***|
// | 12000*****|
// | ****3.1416|
// +------------+