PHP - number_format fails with math operations - php

The PHP function number_format produces weird results when using it with math operations.
Run this...
echo number_format(32545000 - 24343400) . '<br>';
echo number_format(32545000) - number_format(24343400);
Why does the second one produce an answer of "8" instead of the correct answer?

number_format(32545000) returns a string: 32,545,000
number_format(24343400) returns a string: 24,343,400
The strings are converted to int and you get:
32 - 24 = 8

Related

Why am I getting INF when dividing small numbers in PHP

I have two tables in a database. Each have a column (varchar255) with a small number (0-30). I'm only trying to divide those two and this is the result:
If one column has the number 6,575 and the other 1,291 the equation should be 5,09. It outputs 6. Other/most results outputs INF
The numbers come from a foreach loop from the database and this is the code from the picture:
echo $row["ton"]." - ".$row_w["weight"]." - ".$row["ton"] / $row_w["weight"]."<br>";
I have tried bcdiv and that outputs nothing and is_infinite = 1. What am I missing?
You need to convert the values (char strings) to float using floatval before doing the division.
The inf means that the result is infinite because you are dividing by 0 or a very small number as a result of an unexpected value coming from dealing with chars as floats, as the program is not able to understand the decimals in a proper way.
Example:
$var = '578.23';
$float_value_of_var = floatval($var);
and your code could be something like this (only as an indication):
echo $row["ton"]." - ".$row_w["weight"]." - ".floatval($row["ton"]) / floatval($row_w["weight"])."<br>";
Thanks #aynber/#Ash-b for seeing my badly stored values.
$a = str_replace(",", ".", $row["ton"]);
$b = str_replace("," ,".", $row_w["weight"]);
echo $row["ton"]." - ".$row_w["weight"]." - ".$a / $b."<br>";
. instead of ,
Can't set a comment to answer, but case solved.

Arithmetic in the return statement cause unexpected behavior

I'm currently learning PHP from a HTML, CSS, and JS background and I came across some unexpected behavior that interested me. Consequently, I experimented with the following code.
Experiment 1:
It seems that when written the return statement is written like this, everything before the arithmetic is removed/not rendered.
Code:
<?php
function add($num, $num2) {
return $num."+".$num2." = ".$num + $num2."<br>";
}
echo add(10, 7) . add(20, 1);
?>
Outputs:
17<br>
21<br>
Experiment 2:
However, when I change the first variable/parameter from $num to $num2, it seems that every between the first variable and the + operator is removed.
Code:
<?php
function add($num, $num2) {
return $num2."+".$num2." = ".$num + $num2."<br>";
}
echo add(10, 7) . add(20, 1);
?>
Outputs:
14<br>
2<br>
Experiment 3:
After trying it in JS, I realized that putting brackets around the arithmetic equation would output the expected result.
Code:
<?php
function add($num, $num2) {
return $num."+".$num2." = ".($num + $num2)."<br>";
}
echo add(10, 7) . add(20, 1);
?>
Outputs:
10+7 = 17<br>
20+1 = 21<br>
(Also making a $sum variable would fix the problem)
Question:
My question is what causes the unexpected behavior by not putting the brackets around the equation?
The behavior you are seeing is the result of "type juggling".
Because PHP is not strictly-typed, a string can be interpreted as an integer when needed (or assumed to be needed by the interpreter), or vice versa. So the data type is converted, and if you're not careful can cause issues. In many other languages you would get an error if you treated a string like an integer or an integer like a string. JavaScript, for example, has String.parseInt() to explicitly change the type.
What the interpreter is doing is roughly the following, step-by-step:
$num - establish an integer with value 10
10."+" - concatenating an integer with a string
Convert the current output to a string (10 becomes "10"), and append a plus sign
Output is now "10+"
"10+".$num2 - concatenating a string with an integer
Convert the integer to a string and append it
Output is now "10+7"
"10+7"." = " - concatenating 2 strings
Output is now "10+7 = "
"10+7 = ".$num - concatenating a string with an integer
Convert the integer to a string and append it
Output is now "10+7 = 10
"10+7 = 10" + $num2 - arithmetic calculation between a string and an integer
Convert the string to an integer and add it to the next integer.
In this case, when PHP converts a string to an integer, it starts at the beginning of the string and returns all numerals until it hits the first non-number, so "10+7 = 10" pulls out the 10, then hits the + and stops looking for numbers.
Output is now 17;
17."<br>" - concatenation of an integer and a string
Convert the integer to a string and append the <br>
Output is now 17<br>.
For reference:
Documentation on type juggling: http://php.net/manual/en/language.types.type-juggling.php
How does PHP know that you don't want to take this $num."+".$num2." = ".$num and arithmetically add it to this $num2."<br>"? It doesn't, unless you use parentheses to cause the $num + $num2 to happen first.
In the first example:
$num."+".$num2." = ".$num
Equates to the string: 10+7=10, and then:
$num2
Equates to 7.
When you attempt to add them + the string 10+7=10 must be cast to an integer 10 and and when added to 7 gives you 17 then the string <br> is concatenated.
See PHP: String Conversion to Numbers
With parentheses:
$num."+".$num2." = ".($num + $num2)."<br>";
You get string 10+7= concatenated with 10+7 (17) concatenated with string <br>.

How to cut decimal number using PHP

I have a code where I got some numbers like this:
92.682926829268
I'd like to cut them like this:
92.68
This is my code:
<td><?php if (($row['TotalMatch']) > 10){ echo ($row['OK_05'] / $row['TotalMatch']) * 100; } ?></td>
I tried with floor and round but I get that example I showed at the beginning of post ( 92.682926829268 instead of 92.68 )
Thanks for your attention
Regards!
EDIT Could you give me an example with my code? Thanks
Use sprintf() to format the number.
echo sprintf("%.2f", 92.682926829268);
Example:
https://3v4l.org/U87T9
The expression you're trying to format is this:
($row['OK_05'] / $row['TotalMatch']) * 100
So whichever function you decide to use needs to go around that expression.
As to which function to use, you need to select one that returns a string, not a float.
If you use round, and your expression returns a float that rounds to a number with two zeros after the decimal point, the trailing zeros will not be displayed in the result. For example, echo round(92.0006829268, 2) will display 92, not 92.00. So don't use round if you need to be sure that two decimal places are always displayed. round is a math function, not a formatting function.
floor is really not useful at all here, as it returns a number with no decimal places.
A simple way is to use sprintf as shown in some of the other answers.
echo sprintf("%.2f", ($row['OK_05'] / $row['TotalMatch']) * 100);
The first argument to sprintf is "%.2f", which is a format string indicating that the second argument should be displayed as a float with two decimal places. The second argument is your expression.
Using bcdiv as suggested in the other answer will also work, but it works a little differently that sprintf and will produce a slightly different result in some cases.
sprintf will round to the number of decimal places specified, so for example
echo sprintf("%.2f", 926.89 / 10); // outputs 92.69
and bcdiv will truncate instead, so
echo bcdiv(926.89, 10, 2); // outputs 92.68
Whichever one of those works for you, do that.
You can use the round function
$var = 92.682926829268;
$var = round($var, 2)
Or use sprintf (%.2f cuts the number)
$var = sprintf("%.2f", $var);
Try using sprintf like below:
<?php
$mynumber = 98.343434;
echo sprintf('%.2f', $mynumber); // this will output 98.34
You could use bcdiv()
bcdiv($row['OK_05'], ($row['TotalMatch'] * 100), 2);

Format a decimal number in PHP

I'm trying to format specific numbers up to 8 decimals by deleting unnecessary zeros.
My actual code is:
rtrim(sprintf("%.8f", $upto_eight_decimals), '0')
It actually prevents to format a number as 0.00012 into 1.2E-4 or 0.00012000
However, with numbers integer such as 1 it gets converted into 1. but this point is not my expected result (I know because of rtrim deleting all zeros).
UPDATE: rtrim(rtrim(sprintf("%.8f", $upto_eight_decimals), '0'), '.') it looks like working
You can do it this way, Just use number_format:
$upto_eight_decimals = "0.0001200";
$out = number_format((float)$upto_eight_decimals, 8, '.', '');
echo preg_replace("/\.?0*$/",'',$out);
or
echo $out + 0;
This function returns a string.
This will work for you, let me know is it work or not.

How to convert a "decimal string" into an integer without the period in PHP

If I have, say, 8.1 saved as a string/plaintext, how can I change that into the integer (that I can do addition with) 81? (I've got to remove the period and change it into an integer. I can't seem to figure it out even though I know it should be simple. Everything I try simply outputs 1.)
You can also try this
$str = '8.1';
$int = filter_var($str, FILTER_SANITIZE_NUMBER_INT);
echo $int; // 81
echo $int+1; // 82
DEMO.
If you're dealing with whole numbers (as you said), you could use the intval function that is built into PHP.
http://php.net/manual/en/function.intval.php
So basically, once you have your string parsed and setup as a whole number you can do something like:
intval("81");
And get back the integer 81.
Example:
$strNum = "81";
$intNum = intval($strNum);
echo $intNum;
// "81"
echo getType($intNum);
// "integer"
Since php does auto-casting, this should work:
<?php
$str="8432.145522";
$val = str_replace('.','', $str);
print $str." : ".$val;
?>
Output:
8432.145522 : 8432145522
Not sure if this will work. But if you always have something.something,(like 1.1 or 4.2), you can multiply by 10 and do intval('string here'). But if you have something.somethingsomething or with more somethings(like 1.42 and 5.234267, etc.), I don't know what to say. Maybe a function to keep multiplying by ten until it's an integer with is_int()?
Sources:
http://php.net/manual/en/function.intval.php
http://php.net/manual/en/function.is-int.php
Convert a string to a double - is this possible?

Categories