3

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.

ali
  • 10,927
  • 20
  • 89
  • 138
  • Note that you want the values to be *strings* - make sure that this information comes through in samples to avoid confusion by using the correct `array("-001.023", ..)` syntax :) – user2246674 Sep 20 '13 at 00:37
  • PHP don't have "integer" and "float", its just "numeric". If you want to ensure it to be displayed in a specific format, you need to do so converting it to string in the process. – Havenard Sep 20 '13 at 00:37
  • @Havenard The OP is already doing that, fsvo and with limited success (see number_format, etc). – user2246674 Sep 20 '13 at 00:38
  • Yes, I just want to display them in that format, so they would be strings – ali Sep 20 '13 at 00:38

1 Answers1

8

Try using sprintf()

$numbers2[] = sprintf("%+07.3f", $fnum);
John Conde
  • 217,595
  • 99
  • 455
  • 496
  • @Havenard I was trying to figure that out and wasn't getting it. Gonna find an answer of yours to upvote as a thank you. – John Conde Sep 20 '13 at 00:39
  • Use %+07.3f then, it will force the sign. – Havenard Sep 20 '13 at 00:42
  • @Havenard Good call. I forgot that. I ended up with `%+08.3f`: + for sign (as noted), 0 for zero-fill, 8 for *total length* (including sign) and 3 for precision. Using 7 for the length only allows two digits before the decimal. – user2246674 Sep 20 '13 at 00:44