note 45739 added to function.number-format

From: Date: Thu, 16 Sep 2004 20:07:04 +0000
Subject: note 45739 added to function.number-format
Groups: php.notes 
Request: Send a blank email to php-notes+get-76842@lists.php.net to get a copy of this message
// 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 "&nbsp;" $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| // +------------+ ---- Manual Page -- http://www.php.net/manual/en/function.number-format.php Edit -- http://master.php.net/manage/user-notes.php?action=edit+45739 Delete -- http://master.php.net/manage/user-notes.php?action=delete+45739&report=yes Reject -- http://master.php.net/manage/user-notes.php?action=reject+45739&report=yes Search -- http://master.php.net/manage/user-notes.php

« previous php.notes (#76842) next »