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.
Related
At the the moment, I stored values in my mysql database as a decimal value (199,54).
But If I get this value with php (mysql query) and would like to calculate with it:
echo ($row->myValue) / 5;
I get the error:
A non well formed numeric value encountered ...
Where is my mistake?
You can use floatval function to convert decimal value that is fetched from database and then you can use in calculation:
$floatValue = floatval($row->myValue);
Now you can use $floatValue variable in any calculation.
As others have pointed out decimal separator in php is dot (.) not comma (,).
Either change the separator on the DB level to . or run the following anytime you want to deal with numbers stored in the database. First two lines are just an example to get it running locally for me
<?php
$row = new stdClass();
$row->myValue = "15,29";
$myValue = str_replace(',', '.', $row->myValue) / 5;
echo $myValue;
?>
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
this might be a stupid question but I have searched again and again without finding any results.
So, what I want is to show all the decimal places of a number without knowing how many decimal places it will have. Take a look at this small code:
$arrayTest = array(0.123456789, 0.0123456789);
foreach($arrayTest as $output){
$newNumber = $output/1000;
echo $newNumber;
echo "<br>";
}
It gives this output:
0.000123456789
1.23456789E-5
Now, I tried using 'number_format', but I don't think that is a good solution. It determines an exact amount of decimal places, and I do not know the amount of decimal places for every number. Take a look at the below code:
$arrayTest = array(0.123456789, 0.0123456789);
foreach($arrayTest as $output){
$newNumber = $output/1000;
echo number_format($newNumber,13);
echo "<br>";
}
It gives this output:
0.0001234567890
0.0000123456789
Now, as you can see there is an excess 0 in the first number, because number_format forces it to have 13 decimal places.
I would really love some guidance on how to get around this problem. Is there a setting in PHP.ini which determines the amount of decimals?
Thank you very much in advance!
(and feel free to ask if you have any further questions)
It is "impossible" to answer this question properly - because a binary float representation of a decimal number is approximate: "What every computer scientist should know about floating point"
The closest you can come is write yourself a routine that looks at a decimal representation of a number, and compares it to the "exact" value; once the difference becomes "small enough for your purpose", you stop adding more digits.
This routine could then return the "correct number of digits" as a string.
Example:
<?php
$a = 1.234567890;
$b = 0.123456789;
echo returnString($a)."\n";
echo returnString($b)."\n";
function returnString($a) {
// return the value $a as a string
// with enough digits to be "accurate" - that is, the value returned
// matches the value given to 1E-10
// there is a limit of 10 digits to cope with unexpected inputs
// and prevent an infinite loop
$conv_a = 0;
$digits=0;
while(abs($a - $conv_a) > 1e-10) {
$digits = $digits + 1;
$conv_a = 0 + number_format($a, $digits);
if($digits > 10) $conv_a = $a;
}
return $conv_a;
}
?>
Which produces
1.23456789
0.123456789
In the above code I arbitrarily assumed that being right to within 1E-10 was good enough. Obviously you can change this condition to whatever is appropriate for the numbers you encounter - and you could even make it an optional argument of your function.
Play with it - ask questions if this is not clear.
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.
I can't understand why these arrays give me different outputs:
• this value 1/4 came from a table (db)
id | value
...
2 | 1/4
3 | 1/7
echo $matrix[0][2]; //show 1/4
• but if i do = 1/4
echo $matrix[0][2] = 1/4 // show 0.25
this occurs in all fractions values. For example 1/7 in first example show 1/7, but in second show 0.142857142
So, my question is why ? I want always decimal value, but the first code as i said, is not working with decimals.
thanks
In the first example, you are retrieving string values from the database. In the second example, you are evaluation a mathematical expression.
Your best bet would be to do something like:
$t = explode("/", $matrix[0][2]);
echo ($t[0] / $t[1]);
The value from the database is a string and the value you set yourself is a float.
If you are using MySQL you can use mysql_fetch_field to know a field type, wich can be usefull when you're working with MyISAM (MySQL always return strings).
You have the easy/ugly solution:
$var = '1/4';
echo (float)eval('return '.$var.';');
An other solution:
$var = '1/4';
$tmp = explode('/', $var, 2);
$tmp = $tmp[0]/$tmp[1];
echo $tmp;
But I think the best solution is to save the result in your database (0.25 for example) and to cast the results into float when you're getting them.
Cos' in the first example value have a string type and in the second you're calculating math function and the answer have a floating point type.
If u'll use this construction "echo $a = '1/4';" the output will be the same.