PHP - 强制整数转换为浮点数,带有三位小数

ali*_*ali 2 php format integer decimal

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

$numbers1 = array(-1.23, 0.3222, 10, 5.54);
Run Code Online (Sandbox Code Playgroud)

我想要他们的最终格式

$numbers2 = array(-001.023, +000.322, +010.000, +005.054);
Run Code Online (Sandbox Code Playgroud)

我想这样做:

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;
Run Code Online (Sandbox Code Playgroud)

}

这是错误的,我只是不知道如何使用它来实现它.

Joh*_*nde 7

尝试使用 sprintf()

$numbers2[] = sprintf("%+07.3f", $fnum);
Run Code Online (Sandbox Code Playgroud)