user1545478
user1545478

Reputation: 113

Keeping "useless" 0s when performing calculations

This may seem like an odd question, but it's something I couldn't solve on my own. If I were to say, have a number such as 001 assigned to a variable $add, then wanted to perform an operation like this:

$me = $add + 1;

How could I keep the "useless" leading 0s in this number after the operation?

Full overview:

<?php
$add = 001;
$me = $add + 1;
?>

My desired output is 002, but my received output is simply 2. I also wish to be able to do this backwards, say minus 1 from 002 yielding 001 instead of simply 1.

Upvotes: 1

Views: 223

Answers (3)

Alex
Alex

Reputation: 23300

You want to str_pad things up like this:

<?php

$add = 001; //starting number

$number_to_pad = $add + 1; // echoing this would write "2"

$desired_length = 3; // adjust accordingly to how long you want you number to be

$output = str_pad($number_to_pad, $desired_length, '0', STR_PAD_LEFT);

// echo $add; // would write out '1'
// echo $number_to_pad; // would write out '2'
echo $output; // writes '002' as desired    
?>

Upvotes: 0

Brian Agnew
Brian Agnew

Reputation: 272337

You're inadvertently confusing decimal notation with octal notation.

$a = 0123; // octal number (equivalent to 83 decimal)

so if you subtract 001 from 010 you're not going to get 009! (see this calculator for examples)

If you really want to display numbers with leading zeroes, that's an output formatting issue. See this SO answer for more info.

Upvotes: 2

Thilo
Thilo

Reputation: 262684

If you always want the number to have three digits, you can use sprintf

 sprintf('%03d', 2);  # prints "002"

If the number of digits is variable and depends on the original input, you have to first determine how many digits you want, and then put that in the format parameter.

Also, when getting the starting value, make sure that you don't accidentally get it in octal (which should not really happen when parsing an input string, those will be treated as decimal, but careful with literals in the program).

Upvotes: 0

Related Questions