3

我正在尝试将大量数字转换为特定格式,即 +/-NNN.NNN。所以,如果我有这些数字:

$numbers1 = array(-1.23, 0.3222, 10, 5.54);

我希望他们的最终格式是

$numbers2 = array(-001.023, +000.322, +010.000, +005.054);

我正在尝试这样做:

foreach ($numbers1 as $n) {
 $fnum = abs(number_format((float)$n, 3, '.', ''));
 if ($fnum>0 && $fnum<10) { 
     $fnum = '00'.$fnum;
 } else if ($fnum >= 10 && $fnum<100) {
     $fnum = '0'.$fnum;
 }
 if ($n>0) $fnum = '+'.$fnum;
 if ($n<0) $fnum = '-'.$fnum;
 if ($n == 0) $fnum = '+000.000';
 $numbers2[] = $fnum;

}

这是错误的,我只是不知道要使用什么来实现它。

4

1 回答 1

8

尝试使用sprintf()

$numbers2[] = sprintf("%+07.3f", $fnum);
于 2013-09-20T00:33:55.220 回答