PHP- Maintain leading 0 in number [duplicate] - php

I need to add numbers in php without changing the number format like below
$a = "001";
$b = "5";
$c = $a+$b;
Now the result comes like "6" but I need "006" if $a is "01" then the result should be "06".
Thanks

Technically speaking, the $a and $b in your example are strings - when you use the addition operator on them they converted to integers which can't retain leading zeroes. More details on string-to-number conversion are in the manual
Something like this would do it (assuming positive integer strings with leading zeros)
#figure out how long the result should be
$len=max(strlen($a), strlen($b));
#pad the sum to match that length
$c=str_pad($a+$b, $len, '0', STR_PAD_LEFT);
If you always know how long the string has to be, you could use sprintf, e.g.
$c=sprintf('%03d', $a+$b);
Here, % introduces a placeholder, 03 tells it we want zero padded to fill at least 3 digits, and d tells it we're formatting an integer.

Hope this would help you:
<?php
$a="001";
$b="5";
$l=max(strlen($a),strlen($b));
$c=str_pad($a+$b, $l,"0", STR_PAD_LEFT);
echo $c;
?>

For common case. Your code should looks like this.
$a = someFormat($original_a);
$b = someFormat2($original_b); // $b has different format.
$c = someFormat($a + $b);
Or, you need write formatRecognition function.
$a = getValueA();
$b = getValueB();
$c = someFormat(formatRecognition($a), $a + $b);

Related

php for loop with decimal point [duplicate]

Simple maths:
$a=$b/$c; echo $a;
if $b equals to 123.00 and $c equals to 1 then $a becomes 123.
If $b is 123.50, $c is 1, $a is 123.50. But in the former case , I want $a to be 123.00.
It is possible to test whether $a has any non-zero fraction part or not, and then add the trailing zeros as necessary.
But I am looking for php functions to do the same thing. Possible?
EDIT :
What if I do not want the commas from number_format there ?
Use sprintf("%0.2f",$a);. docs
Use the number_format function. If you don't want comma separators, set all four parameters of the function like so (the thousands separator is the fourth parameter):
$number = number_format(1234, 2, '.', '');
Yup, using https://www.php.net/manual/en/function.number-format.php function like this:
$a = 123;
$answer = number_format($a,"2");
echo $answer;

Adding comma and dot separated values in PHP

The current application I'm building needs to let the user enter values like "3,040,400.00".
I noticed that PHP doesn't know how to add or substract values with that format?
How can I perform this operations keeping in mind that the user will enter values formatted as above?
For example:
$a = '3,040,400.00';
$b = '23,949.00';
echo $a - $b; // returns -20
You should simply use str_replace() in order first to remove to commas inside the string. You cannot outright do arithmetic on them. Then after converting them properly you can use number_format() in the end. Consider this example:
$a = '3,040,400.00';
$b = '23,949.00';
$a = (float) str_replace(',', '', $a);
$b = (float) str_replace(',', '', $b);
$total = $a - $b;
echo number_format($total, 2, '.', ','); // should output : 3,016,451.00
Fiddle
$a = str_replace(",","",$a);
same for b
for outputting your values you can use the php-function number_format():
http://www.php.net/manual/en/function.number-format.php

Concatenation-assignment in PHP

I am learning PHP and I just read about Assignment Operators and I saw this
$a .= 5 which means $a equals $a concatenated with 5. To test this I coded a simple script
<?php
$a = 12345;
$a .=6;
$b = 12345;
$b .=006;
$c = 12345;
$c .=678;
echo " a=$a and b=$b c=$c" ;
?>
the output was a=123456 and b=123456 c=12345678.My question is why the b isn't equal with 12345006? Is it because treats 6 == 006?
Because 006 is treated as the octal number 6, which is the converted to the string "6", and concatenated to "12345" (which is the number 12345 converted to a string).
Use $b .= "006", and the result will be 12345006.
Because numbers with leading zeroes are treated as octals. if the concatenation would've included the leading zeroes, then 006 would've been interpretted as a string, which makes no sense, because it hasn't got quotes around it.
If you want 006 to be treated as a string, write it as one: '006'. Leave it as is, and it'll be interpreted as an octal:
$b = $a = 123;
$a .= 8;
$b .= 010;//octal
echo $a, ' === ', $b, '!';//echoes 1238 === 1238!
Just as an asside: yes, those are comma's/. echo is a language construct to which you can push multiple values, separated by comma's. The upshot of using comma's is that the values aren't concatenated into a single string before being pushed to the output stream.
This means that it is (marginally faster). The downsides: there aren't any AFAIK.
In case you're interested in the internals of PHP, I've explain this a bit more detailed here...
Just try b as a string:
$b.= '006';
Then you will get output 12345006.

php, add trailing zeros if the number is integer

Simple maths:
$a=$b/$c; echo $a;
if $b equals to 123.00 and $c equals to 1 then $a becomes 123.
If $b is 123.50, $c is 1, $a is 123.50. But in the former case , I want $a to be 123.00.
It is possible to test whether $a has any non-zero fraction part or not, and then add the trailing zeros as necessary.
But I am looking for php functions to do the same thing. Possible?
EDIT :
What if I do not want the commas from number_format there ?
Use sprintf("%0.2f",$a);. docs
Use the number_format function. If you don't want comma separators, set all four parameters of the function like so (the thousands separator is the fourth parameter):
$number = number_format(1234, 2, '.', '');
Yup, using https://www.php.net/manual/en/function.number-format.php function like this:
$a = 123;
$answer = number_format($a,"2");
echo $answer;

Adding string with number in php

$a = "3dollars";
$b = 20;
echo $a += $b;
print($a += $b);
Result:
23
43
I have a question from this calculation.$a is a string and $b is number.I am adding both and print using echo its print 23 and print using print return 43.How is it
It casts '3dollars' as a number, getting $a = 3.
When you echo, you add 20, to $a, so it prints 23 and $a = 23.
Then, when you print, you again add 20, so now $a = 43.
The right way to add (which is technically concatenating) strings is
$a = 7;
$b = "3 dollars";
print ($a . $b); // 73 dollars
The + operator in php automatically converts string into numbers, which explains why your code carried out arimethic instead of concatenation
PHP automatically associates a data type to the variable, depending on its value. Since the data types are not set in a strict sense, you can do things like adding a string to an integer without causing an error.
In PHP 7, type declarations were added. This gives us an option to specify the expected data type when declaring a function, and by adding the strict declaration, it will throw a "Fatal Error" if the data type mismatches.
To specify strict we need to set declare(strict_types=1);. This must be on the very first line of the PHP file. Then it will show fatal error and if you didn't declare this strict then it convert string into integer.
If you need both the values, return them in an array
PHP treats '3dollars' as a integer 3 because string starting with integer and participating in arithmetic operation, so
$a = "3dollars";
$b = 20;
echo $a += $b;
it echo 23; //$a=$a+$b;
now $a = 23 + 20;
print($a += $b); //$a=$a+$b;
it print 43;
Since You have created a variable for the two, it stores the result of each, so when you added $a to 20 it will echo 23 which stores in the system, them when you print $a which is now 23 in addition to $b which is 20. You will get 43.

Categories