2012-07-05 33 views
2

我试图写,将采取不同量的阵列和对准小数位,通过用较小的长度大于与数加入 适量至每数的函数最长的长度。对齐小数货币的数组值

似乎很长,虽然,我不知道是否有人对我怎么可能让一些有识之士更短,更高效。

$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 &nbsp; for each number of characters 
      //between the two decimal locations 
      $i = "&nbsp;" . $i; 
      $c++; 
     } 

    } 

    return $arr; 
} 

它的工作原理okkaaay ...看起来真的很详细。我相信有一百万种方法可以使它变得更短,更专业。感谢您的任何想法!

回答

2

代码:

$array = array(12, 34.233, .23, 44, 24334, 234);; 
foreach($array as $value) $formatted[] = number_format($value, 2, '.', ''); 
$length = max(array_map('strlen', $formatted)); 
foreach($formatted as $value) 
{ 
    echo str_repeat("&nbsp;",$length-strlen($value)).$value."<br>"; 
} 

输出:

&nbsp;&nbsp;&nbsp;12.00<br> 
&nbsp;&nbsp;&nbsp;34.23<br> 
&nbsp;&nbsp;&nbsp;&nbsp;0.23<br> 
&nbsp;&nbsp;&nbsp;44.00<br> 
24334.00<br> 
&nbsp;&nbsp;234.00<br> 

渲染的浏览器:

12.00 
    34.23 
    0.23 
    44.00 
24334.00 
    234.00 
+0

这是短得多!谢谢! – 1252748 2012-07-05 16:41:08

+0

这要求您使用带有等宽字体的字体和与其宽度匹配的nbsp。如果您需要在HTML表格中对齐数字,我创建了一个没有这些限制的简单jQuery插件:https://github.com/ndp/align-column。 – ndp 2013-04-10 18:54:57

1

你有没有考虑过使用HTML元素的CSS一起对准为你做这个?

例如:

<div style="display:inline-block; text-align:right;">$10.00<br />$1234.56<div>

这将缓解使用空格键手动调整对齐问题。由于您对齐到右侧,并且有两位小数,所以小数将按照您的意愿排列。你也可以做到这一点使用<table>并在这两种情况下,你可以简单地通过JS检索完整的价值如果需要的话。

最后,使用空格假定您使用的是固定宽度字体可能不一定是这样。 CSS对齐允许你更加雄辩地处理这个问题。

+0

谢谢。虽然css可以用来完成类似的想法,我宁愿使用PHP来编写脚本。 – 1252748 2012-07-05 16:43:21

2

是使用空间用于显示的要求?如果你不介意“30”现身为“30.000”您可以使用number_format做大部分的工作适合你,你想通了小数使用的最大数量之后。

$item = "40"; 
$len = 10; 
$temp = number_format($item,$len); 
echo $temp; 

另一种是使用sprintf到格式:

$item = "40"; 
$len = 10; 
$temp = sprintf("%-{$len}s", $item); 
$temp = str_replace(' ', '&nbsp;',$temp); 
echo $temp;