我尝试编写一个函数,该函数将采用不同数量的数组并对齐小数位,方法是将适当数量的
添加到长度小于长度的数字的每个数字。
虽然它看起来很长,但我想知道是否有人对我如何使它更短、更高效有一些见解。
$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;
}
它工作奥卡伊...只是看起来真的很啰嗦。我相信有一百万种方法可以使其更短、更专业。感谢您的任何想法!
代码:
$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(" ",$length-strlen($value)).$value."<br>";
}
输出:
12.00<br>
34.23<br>
0.23<br>
44.00<br>
24334.00<br>
234.00<br>
由浏览器呈现:
12.00
34.23
0.23
44.00
24334.00
234.00
使用空格是显示器的要求吗? 如果您不介意将"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(' ', ' ',$temp);
echo $temp;
您是否考虑过将HTML元素与CSS对齐一起使用来为您执行此操作?
例如:
<div style="display:inline-block; text-align:right;">$10.00<br />$1234.56<div>
这将缓解使用空格手动调整对齐方式的问题。由于您向右对齐并且有两个小数位,因此小数点将根据需要排列。您也可以使用<table>
执行此操作,在这两种情况下,如果需要,您都可以通过 JS 简单地检索完整值。
最后,使用空格假设您使用的是固定宽度的字体,但情况不一定如此。CSS 对齐允许您更雄辩地处理这个问题。