PHP - Force integer conversion to float with three decimals

不想你离开。 提交于 2020-01-10 04:28:05

问题


I am trying to convert a big array of numbers to a specific format which is +/-NNN.NNN. So, if I have these numbers:

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

I want their final format to be

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

I am trying to do it like this:

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;

}

This is wrong and I just don't know what to use in order to achieve it.


回答1:


Try using sprintf()

$numbers2[] = sprintf("%+07.3f", $fnum);


来源:https://stackoverflow.com/questions/18907129/php-force-integer-conversion-to-float-with-three-decimals

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!