我試圖寫,將採取不同量的陣列和對準小數位,通過用較小的長度大於與數加入
適量至每數的函數最長的長度。對齊小數貨幣的數組值
似乎很長,雖然,我不知道是否有人對我怎麼可能讓一些有識之士更短,更高效。
$arr = array(12, 34.233, .23, 44, 24334, 234);
function align_decimal ($arr) {
$long = 0;
$len = 0;
foreach ($arr as &$i){
//change array elements to string
(string)$i;
//if there is no decimal, add '.00'
//if there is a decimal, add '00'
//ensures that there are always at least two zeros after the decimal
if (strrpos($i, ".") === false ) {
$i .= ".00";
} else {
$i .= "00";
}
//find the decimal
$dec = strrpos($i, ".");
//ensure there are only two decimals
//$dec+3 is the decimal plus two characters
$i = substr_replace($i, "", $dec+3);
//if $i is longer than $long, set $long to $i
if (strlen($i) >= strlen($long)) {
$long = $i;
}
}
//locate the decimal in the longest string
$long_dec = strrpos($long, ".");
foreach ($arr as &$i) {
//difference between $i and $long position of the decimal
$z = ($long_dec - strrpos($i, "."));
$c = 0;
while ($c <= $z ) {
//add a for each number of characters
//between the two decimal locations
$i = " " . $i;
$c++;
}
}
return $arr;
}
它的工作原理okkaaay ...看起來真的很詳細。我相信有一百萬種方法可以使它變得更短,更專業。感謝您的任何想法!
這是短得多!謝謝! – 1252748 2012-07-05 16:41:08
這要求您使用帶有等寬字體的字體和與其寬度匹配的nbsp。如果您需要在HTML表格中對齊數字,我創建了一個沒有這些限制的簡單jQuery插件:https://github.com/ndp/align-column。 – ndp 2013-04-10 18:54:57