Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP - Force integer conversion to float with three decimals

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.

like image 923
ali Avatar asked Jun 15 '26 11:06

ali


1 Answers

Try using sprintf()

$numbers2[] = sprintf("%+07.3f", $fnum);
like image 76
John Conde Avatar answered Jun 17 '26 20:06

John Conde



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!