0

I have the value as $title =10 and I want to minus it with 01.So my code is:

echo  $minus = round(($title - 01),2);

I want the result $minus = 09 but this code not like this it still have the result $minus=9. Anyone help me please,Thanks.

Maly.nu Cute
  • 35
  • 1
  • 4
  • 2
    Numbers cannot have leading zeroes. You're asking how to format a string. – SLaks Jan 11 '13 at 03:42
  • are you implementing it as an octal or a string? – ianace Jan 11 '13 at 03:44
  • `var_dump($title)` outputs `4`, so it seems despite how you write, as long as it's a valid number, PHP stores it in the most common form. Convert the result to a string so you can add zeros. – Passerby Jan 11 '13 at 03:46

5 Answers5

0

The problem is that PHP is not strongly typed, and round() returns a number, which automatically has the leading zero stripped. Try:

$minus = "0" . round(($title - 01),2);
0

PHP is evaluating your 0-prefixed numbers to their base value -- 04 and 01 are 4 and 1 respectively.

If you want them to be output with a leading 0, try using a number formatter, or string padding or simply append them to the string, "0"

shortstuffsushi
  • 2,271
  • 19
  • 33
0

What's happening is that round() returns an integer. Which means it won't have any 0's before it. If you want it to return 0's before it, try

str_pad(round(($title - 1), 2), 2, "0");

That will make it always append a 0 before the number if it's only 1 number, but if it's 10 or 15 or something, it won't append a 0

Gareth Parker
  • 5,012
  • 2
  • 18
  • 42
  • Almost; the problem is that str_pad automatically pads to the right of the string, so if $title were 04, your result would be 30. You can specify `STR_PAD_LEFT` as the fourth argument in str_pad() though, and it would pad to the left. – Chris Forrence Jan 11 '13 at 03:49
  • So close, I always forget about that until I test it – Gareth Parker Jan 11 '13 at 03:51
  • I hear you; I ran a quick search for a way to run PHP code online, and I did come across this. It should help in the future: http://writecodeonline.com/php/ – Chris Forrence Jan 11 '13 at 03:54
0
echo str_pad(intval($title) - 1, 2, "0", STR_PAD_LEFT);

This will pad your result with a 0 if the result is only one digit; otherwise, it will not pad. For a leading zero always, you can replace the 2 with strlen($title)

Chris Forrence
  • 10,042
  • 11
  • 48
  • 64
0

Try this..

$i=04-01;
echo sprintf('%02s', $i);  
웃웃웃웃웃
  • 11,829
  • 15
  • 59
  • 91
  • `echo sprintf()` is an "antipattern". There is absolutely no reason that anyone should ever write `echo sprintf()` in any code for any reason -- it should be `printf()` without `echo` every time. – mickmackusa Apr 09 '22 at 02:45