2012-07-05 76 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;