我试图写,将采取不同量的阵列和对准小数位,通过用较小的长度大于与数加入
适量至每数的函数最长的长度。对齐小数货币的数组值
似乎很长,虽然,我不知道是否有人对我怎么可能让一些有识之士更短,更高效。
$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