Basic Multiplication with PHP - php

Consider the below code in PHP
$a = 8425996523 * 121212713;
$b = sprintf('%.2f', $a);
$mul = gmp_mul("8425996523", "121212713");
Output is
1.0213378982814E+18
1021337898281396864.00
1021337898281396899
The actual answer is 1021337898281396899. Hence, it is clear that we need to use any libraries like gmp_mul to do arithmetic with large numbers.
My question is, how to identify such errors?
ie, when PHP does a calculation like
8425996523 * 121212713
, how can I identify that the result is not correct?
One way I see is to check for E and assume that whenever we forcefully convert such numbers, the errors exits.

Use
$b = sprintf('%.2d', $a);
Instead of
$b = sprintf('%.2f', $a);
Here's a screenshot of the source code to show the difference:

Related

PHP Why does explicit typecast + 1 work, but not with an increment operator

Firstly, let's say for the sake of argument, the reasons why I want to do this is arbitrary and not solution specific.
I would like to explicitly cast a variable, regardless of input, and increment it after typecasting, not with the original variable. For example, not like this:
$num = "47 downvotes";
(int) ++$num;
I am looking for something similar to this psuedo-coded version, or a variation thereof:
$num = "value";
++((int) $num);
For PHP being loose, I was really hoping this to work, but I can't use the Pre-increment operator without creating another variable first.
$num = "value";
$cast = (int) $num;
echo ++$cast;
While testing, I found that PHP is loose enough for it to work by adding a digit however:
$num = "47 dogs";
echo ((int) $num) + 1;
I also understand my first example, isn't wrong, but again, for arbitrary reasons, I need to make sure it has been casted prior to incrementing/decrementing.
So the question is, why is PHP loose enough for the latter to compile?
If you could provide resources or links to any reputable reading material I would appreciate that as well.
With explicit typecasting you have to assign the result to a variable. In your examples, you are trying to increment variables when they are strings, which fails or doesn't produce the result you expect in combination with typecasting.
Look at your original example:
<?php
$num = "47 downvotes";
echo $num . PHP_EOL;
echo ++$num;
The result of incrementing a string isn't what you expect it to be:
47 downvotes
47 downvotet
So your original supposition is that PHP doesn't work when in fact it does.
$num = "47 downvotes";
echo (int) ++$num . PHP_EOL;
$num2 = "47";
echo (int) ++$num2;
Output:
47
48
The process of typecasting is inherently complicated, and has all sorts of behavior that can produce unexpected results, and just isn't the catchall dependable "fix your input" that will let you find the numeric portion of any string available to you in a single line of code, but that doesn't mean that PHP is flawed.

PHP ignore dollar sign

PHP
<?php
$a = $offer->service_original_price_display;
$b = $offer->service_discounted_price_display;
$c = $a - $b;
?>
However I am getting this error: A non-numeric value encountered since service_original_price_display is '$500' and service_discounted_price_display is '$300'. I assume it is because both contains the dollar sign hence PHP is not able to perform the equation. Is there any solution to this? Thanks!
$a = str_replace("$", "", $offer->service_original_price_display);
$b = str_replace("$", "",$offer->service_discounted_price_display);
$ is string
use trim($a, '$'); to remove both side $ sign
You can use substr, if you know the first place is always occupied by a $ from an error standpoint, removing the $ ( with str_replace ) is probably better. But, as those answers where already posted. I get the scraps ( lol ).
$a = '$500';
$b = '$300';
$c = substr($a,1) - substr($b,1);
echo $c;

Initialize variable as float

Never had to do such a basic thing before. How do I initialize a variable as a float before doing logic? Do either of these examples make sense?
$var = 0.0;
$var = (float) 0;
Both make sense, the first is shorter, with the second you can initialized with a dynamic value, your choice !
EDIT : But I agree with #Niet the Dark Absol, it poorly matters since you use test function such as ctype_digit, or is_numeric.
from http://php.net/manual/en/language.types.float.php
Floating point numbers (also known as "floats", "doubles", or "real
numbers") can be specified using any of the following syntaxes:
<?php
$a = 1.234;
$b = 1.2e3;
$c = 7E-10;
?>
so defining a float by using $var = 0.0 is correct. While casting is not technically incorrect I don't believe it's something you should use when you don't need to.
Try to use number_format.
For example:
$number = 20;
echo number_format($number,2) // will output 20.00
// number_format($number,$decimals,$dec_point,$thousands_sep)

PHP- Maintain leading 0 in number [duplicate]

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);

What Does the & (ampersand) symbol mean in this circumstance?

I'm new to php and mysql. Im following a tutorial from phpacademy on youtube. There is a section that is of form data, but everyone who followed the tutorial (myself included) got undefined index errors. I fixed it with & (ampersand) symbol. But what does it do in the follow circumstances?? Why does putting the & symbol in front of the $ stop the error? Is it the same as # and is it just suppressing the error or did it actually fix it?
$submit = &$_POST['submit'];
It means instead of assigning the value to $submit, assign a reference to the value to $submit.
If you are familiar with C and pointers, it is like a pointer to the value that is automatically dereferenced when you access it. However, PHP doesn't allow things pointer arithmetic or getting the actual memory address (unlike C).
$a = 7;
$b = $a;
$c = &$a;
$c = 5;
echo $a, $b, $c; // 575
CodePad.
To stop the error you mentioned, you can use a pattern such as...
$submit = isset($_POST['submit']) ? $_POST['submit'] : 'default_value';
...or...
$submit = filter_input(INPUT_POST, 'submit');

Categories