PHP not dividing correctly - php

I have some PHP code that is dividing two numbers that are pulled from a mySQL database however it is not computing correctly. When I echo $comm and $total_fix individually, the numbers are correct. However, when I echo the division of the two it is not the correct answer. Both numbers are DECIMAL(10,0) data type in the database. Below is the PHP code
$percent_comm = $comm / $total_fix;
$percent_comm = number_format($percent_comm, 2, '.', ',');
echo "<td align=\"center\">".$percent_comm."</td>";
here $comm = 2700, $total_fix = 75 but $percent_comm is computing to be 0.03 when it should be 36

From what I see on your comments, you are getting the $comm variable as a string with a comma, because of the format. I suggest to convert the formatted string into a valid number.
Mean while I'll recomend this:
$comm = '2,700';
$comm = str_replace(',','',$comm);
That remove the comma from your number.

From the variable names, you want to know $comm as a percentage of $total_fix. Your code almost does this: You correctly divide $comm/$total_fix, and it correctly gives you 0.027. But you got it backwards when you checked by hand: 36 is the result of dividing 2700/75 (i.e., $total_fix/$comm)
But to get a percentage, multiply by 100 the result of the division:
(75.0 / 2700) * 100 = 2.7 percent.
That's what your code should be getting.

Related

Integer value ignoring zeros and returning full number

I'm looking to create a PHP Range loop
In a first and second number in the range, but have noticed the first number which is
00006
Is being rounded down / flattened to show "6".
So when I echo the first number value I get "6" back. I need it to be "00006"
Then the next number will need to be 00007 and so on, via the range loop.
My PHP code at present is :
$first_number = 00006;
$last_number = 11807;
foreach(range($first_number, $last_number) as $id)
{
echo $id;
}
How do I go about making sure that the number has the previous 0's in it?
You can do it by using printf() function.
See the documentation : printf
First of all in PHP, a number starting with zero is treated as octal number, But I guess range() function converts it as decimal. So if you want to start it with 20. Like $first_number = 00020; then the output will be start with 16 not 20.
So, if you want the output starting with 0's, then you can do like this:
$first_number = 6;
$last_number = 11807;
foreach(range($first_number, $last_number) as $id)
{
printf("%05d",$id);
}

How to count multiple variables with strlen

I am looking to count the length of strings in multiple variables and add them together to get the total count.
I have tried strlen but have either messed up the syntax or have not used the proper code.
//$_SESSION['var1'] and $_SESSION['var2'] will each be numbers from -30.0 to 1000.0. I need the lengths of the two variables to be added. I need the negative sign(s) and decimal separators, or dots, to be counted.
$_SESSION['var_array'] = $_SESSION['var1'].$_SESSION['var2'];
$_SESSION['var_count'] = strlen($_SESSION['var_array']);
or
$_SESSION['var_count'] = strlen($_SESSION['var1'])+strlen($_SESSION['var2']);
Various results are observed. Sometimes the correct number IS observed but usually not.
The problem is that just storing numeric values doesn't maintain trailing decimals if they are 0. You could alternatively store them as strings, which will maintain the values exactly as you want them or format the numbers to ensure they contain the right format. The following code shows what I mean...
$_SESSION['var1'] = -30.0;
echo $_SESSION['var1'].PHP_EOL; // Gives -30
$_SESSION['var1'] = number_format($_SESSION['var1'], 1);
echo $_SESSION['var1'].PHP_EOL; // gives -30.0
$_SESSION['var2'] = "1000.0";
echo $_SESSION['var1'].PHP_EOL; // gives 1000.0
$_SESSION['var_array'] = $_SESSION['var1'].$_SESSION['var2'];
echo strlen($_SESSION['var_array']); // gives 11

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.

How to calculate using a POST variable?

I need to multiply this POST variable by 12. As an example, if the amount was 10, the result should say:
Amount: 120
Here's my code so far:
Amount :'.$_POST['my_amount'].'<br/>
I tried to run the calculation in another variable, but this doesn't seem to work:
$result = ($_POST['my_amount'])*12;
or maybe it works and my output code is not working:
$vl_text='';
Amount :'.$_POST['my_amount'].'<br/>'.;
If you want your output to resemble your first example.,.. Amount:120 your missing chunks in each of the following 3 examples. first ensure that your $_POST variable is a valid one and set it to a new variable so you can print out the variable if you need to ...
// if you only expect $_POST['my_amount'] to contain integers...
if(is_int(intval($_POST['my_amount']))){
$my_amount = intval($_POST['my_amount']) * 12;
// or if you expect $_POST['my_amount'] to possibly contain a decimal
if(is_float(floatval($_POST['my_amount']))){
$my_amount = floatval($_POST['my_amount']) * 12;
intval ensures that a variable is cast as an integer if it can be, while not entirely necessary as multiplying in php will do this...its good practice to check any variables that you are using for and math functionality.
floatval does the same for for numbers with decimal. as an integer has to be a whole number if your variable could numbers that could contain decimals... use floatval
all of your examples then need to specify to print/echo the string....so
// your second line
echo 'Amount :'.$my_amount .'<br/>';
// your fourth line...
$vl_text='Amount: '.$my_amount;
echo $vl_text;
}
The most logical explanation is that you get string from POST. A good way to achieve what you want is to convert the POST value to int but keep in mind that it could not be numerical.
$int = (is_numeric($_POST['my_amount']) ? (int)$_POST['my_amount'] : 0); //If POST value is numeric then convert to int. If it's not numeric then convert it to 0
$_POST['my_amount'] = 150;
$data = $_POST['my_amount'] * 12;
echo $data;
Result will be 1800

wrong unique number length

I generate an unique security code with this every time user login:
$code = substr(str_shuffle(str_repeat("0123456789", 4)), 0, 4);
it seems works but sometimes it generate 3 number instead of 4. also this problem occurred with rand() in past, then i decide to use str_shuffle + str_repeat.
also i insert this code in db with integer data type and length is 6.
what did i wrong or missed?
or is it a bug?
While I can't immediately say why your code sometimes returns only 3 digits, I find myself wondering why you don't create this 4-digit (call it a PIN?) code through the more numerically appropriate rand? For example, since you are going for a 4-digit PIN (between 0000 and 9999), I might write it like:
$code = rand(0, 9999);
$code = substr("000$code", -4);
That is much clearer as to its purpose (generate a random number, guarantee it's 4 digits), and less esoteric than str_repeat/str_shuffle.
EDIT (after learning $code is inserted into an integer DB field)
Why is your random string of 4 digits sometimes turning into 3 digits? Because you are inserting the value into an integer column. Either the DB or the DB Driver will attempt the moral equivalent of:
$code_to_insert = (int)$code;
at which point, if the number is less than 1000, you would get three digits.
Further, if you run your code enough times as it currently stands, you should get PIN lengths of 2 and 1 as well:
0 - 9 = ( 10 / 10000) -> 0.1% of the time
10 - 99 = ( 90 / 10000) -> 0.9% of the time
100 - 999 = ( 900 / 10000) -> 9.0% of the time
1000 - 9999 = (9000 / 10000) -> 90.0% of the time
A possible fix, given the current setup of your code and DB, might be to ensure the PIN length when you pull it out of the DB. You could use the same trick as above:
$sql = "SELECT code FROM ...";
...
$code = $row['code'];
$code = substr("000$code", -4);
Since you're storing the result in an integer field, it's not being stored as separate digits, just as a number. So it doesn't know anything about leading zeroes.
When you later retrieve the value, you can convert it to a string with leading zeroes using the str_pad function:
$code = str_pad($num, 4, '0', STR_PAD_LEFT);
The other option would be to change the datatype in the database to CHAR(4) instead of INT.
Try this:
$code = str_pad($num, 4, '0', STR_PAD_LEFT);

Categories