I have done this calculation:
$number = round(count($exc)/ count($grades),2,PHP_ROUND_HALF_UP);
When save,I have to save it into a field of an existing table which is a longtext type. The numbers got saved but become very long, something like 0.200000000000000011102230246251565404236316680908203125
I think this might cause extra db storage. When I query the numbers, they are still rounded as 2 digital. So, that's an extra converting job. I would like to learn how to save those numbers as rounded number?
You can use PHP sprintf function coupled with format specifier like so:
$number = sprintf("%.3f", round(count($exc)/ count($grades),2,PHP_ROUND_HALF_UP));
If you need more info about that take a look at sprintf PHP documentation here http://it2.php.net/manual/en/function.sprintf.php .
Related
I have a PHP code that will compute the balance of the quantity but it gives me a negative value as a balance quantity as shown in the image below.
I tried to check the quantities if what's causing the problem and try to var_dump the quantity. after checking using var_dump, it shows that the data type of my quantity is string while my balance quantity is float.
so far, I have my code below:
$query_po_quantity = mysqli_query($new_conn, "SELECT quantity, po_number FROM purchase_order WHERE supplier_name = '$supplier_name' AND category_name = '$category_name' AND activity = '$activity' AND description = '$description'");
$row = mysqli_fetch_assoc($query_po_quantity);
$po_quantity = $row['quantity'];
$po_number = $row['po_number'];
$query_rr_quantity = mysqli_query($new_conn, "SELECT SUM(total_received) AS quantity FROM receiving_reports WHERE po_number = '$po_number' AND category_name = '$category_name' AND activity = '$activity' AND description = '$description'");
$row = mysqli_fetch_assoc($query_rr_quantity);
$rr_quantity = $row['quantity'];
$balance = $po_quantity - $rr_quantity;
$supplier_name = preg_replace('/\\\\/', '', $supplier_name);
echo $po_quantity.' - '.$rr_quantity.' = '.$balance.'<br />';
This is the output:
how can I get the actual balance?
The reason you're getting an incorrect result when calculating 0.42 - 0.420000000000000000004 is due to errors with floating point precision. This is due to the way floating point numbers are stored, and both MySQL and PHP are susceptible to floating point errors if done incorrectly, but they also both have ways to prevent them when you do need highly precise calculations. With floating point types only the approximate value is stored and attempts to treat them as exact values in comparisons may lead to problems.
For PHP, this means you need to use either the arbitrary precision math functions or gmp functions. For MySQL, you need to be storing the numbers using the DECIMAL format with the desired precision you require.
First thing's first, you need to change the data type of your column in MySQL to DECIMAL, not a string. Strings are inappropriate to store numbers. Even if you were using a FLOAT or DOUBLE to store your values
your code may have actually worked, because these values likely would have been rounded.
Next, seeing as the value 0.420000000000000000004 came from a string stored in your database, I'm assuming the error stems from whatever calculations you did using PHP beforehand when you were calculating the value to be inserted. You will need to update this code to use precise math.
Use number_format:
$rr_quantity = number_format($row['quantity'], 2);
Float variable range 1.7E-308 and 1.7E+308 so it's give 15 digits of accuracy. Use number format
I want to make a excel file by fetching data from database. Every thing works fine but the phone number field return unknown value in excel sheet but it displays correct value in browser.
<?php
include('connection.php');
header( "Content-Type: application/vnd.ms-excel" );
header( "Content-disposition: attachment; filename=spreadsheet.xls" );
$q = mysql_query("select * from members order by id desc");
echo 'First Name' . "\t" . 'email' . "\t" . 'Phone' . "\t". 'address' . "\t". 'Membership Number' . "\t". 'Membership Category' . "\n";
while($r = mysql_fetch_array($q))
{
$name = $r['name'];
$email = $r['email'];
$phone = $r['phone'];
$address = $r['address'];
$mem_num = $r['mem_num'];
$mem_cat = $r['mem_category'];
echo "$name"."\t"."$email"."\t"."$phone"."\t"."$address"."\t"."$mem_num"."\t"."$mem_cat"."\n";
}
mysql_close($con);
?>
I believe you are confusing data-types here. A phone number for instance, is not a number. But it's called a number! Yeah I know, because it has a lot of numbers in it, but still, it isn't a number... Why?
A phone number is indeed constructed of a set of numerals - the symbols that represent a number - but that doesn't make it a number yet. Compare letters and words; a word is constructed of a set of letters, but not every set of letters is a word. For example: dfslkwpdjkcnj is not a word, not in a language I know of at least... And if it would be a number, how would you add-up two phone numbers? Or how would you divide a phone number by another one? Would that be something like [grandma's phonenumber] / [mom's phonenumber] = [my phonenumber]?
So, to store a phone number in a database, a varchar would be a more suitable column type. For example international phone numbers start with either a + sign, or double zero (00). Both of them can not be stored in a numeral field type. The + isn't a numeral sign, or is used to designate a positive number, and will be cut off. Leading zero's in a number have no function at all, and will be cut off as well...
So bottom line; in your database, use a varchar to store a phone number, and use conversion functions to format a phone number to your liking. There are almost certainly a dozen of algorithms to be found to format a phone number to some kind of a standardized format.
Then back to your excel: your aren't creating an excel file, but a csv file, and you're giving it an excel mime-type. But that would be the same to give someone a cd and say it is a dvd. If you put the cd in a dvd player, it will almost certainly be able to play it, but it is mere luck then wisdom that it does.
Creating an excel file isn't as easy as setting the mime-type, as you can't expect the browser to know how to convert text to an excel file, as it does not know about excel's internals. So if you reaaally want to create an excel file, and set the data types of certain columns, use a library like phpExcel or any other available, if you don't want to create a library yourself that is.
have you tried expanding(stretching) phone column in your excel file? sometime if column is small and numbers are big, excel displays number like(1.23+09) this.
If stretching column does not work. you can convert numbers into string and then put them in excel file
sorry i can't add this in comment as i don't have privilege to comment yet.
If with your API you are able to format cells, that's what you would need to do. You are storing your phone number as a BigInt instead of as a String. I have always stored phone numbers as Strings.
Excel is interpreting your data correctly--as a number, not as text. If you wish to continue to store your phone number as a BigInt (which I don't recommend), you would need to convert it to a String before writing it out to Excel. Or, if your API permits, write it out to Excel as a number, but then apply cell formatting to bring it to the formatting you expect.
I was trying to export database query to CSV and the need arised to use different decimal comma. It seems impossible to change the decimal comma in MySQL, so I tried in PHP:
setlocale(LC_NUMERIC, "cs_CZ");
But it seems that all the database functions like mysql_fetch_row and mysql_fetch_assoc are retrieving data of type string instead of double:
$res = mysql_query("select 50/3");
$row = mysql_fetch_row($res);
var_dump($row); // $row[0] is of type "string"
So in general PHP already doesn't have data of type double, but only strings!
So is there some general, clean way to specify output of the decimal point?
I ended up converting the strings using str_replace('.', ',', $row[0]) but this is ugly for two reasons:
you have to know which field is of type double
it's a dirty string job.
I don't know which database client/driver you're using but there is something like mysql_field_typeDocs which gives you the type based on it's offset, like 0.
This should do the job to find out if a certain column needs re-formatting or not.
To reformat, there is number_formatDocs.
With these you can do the conversion automatically.
Edit: Regarding your comments:
If you want to get PHP datatypes mapped, consider using the MySQL Native DriverDocs. Use it together with PDO:
Advantages of using mysqlnd for PDO
mysqlnd returns native data types when using Server-side Prepared Statements, for example an INT column is returned as an integer variable not as a string. That means fewer data conversions internally. Source
So depending of what you try to achieve, use the right tool.
See as well the multiple options you have when fetching data from a PDO StatementDocs.
// French notation
$nombre_format_francais = number_format($number, 2, ',', ' ');
Try
number_format($row[0], 2, ",", ".");
That should change the format of the number. (german format)
I have a service on the internet where people post pictures and a short string is generated. Only one can be used ever. However, I am getting into duplicates in the database and I am seeing major problems.
Here's what I am using:
$id=rand(10000,99999);
$short_string = base_convert($id,20,36);
What would be the best way to fix it? Check from the database and keep looping till it doesn't match one? What if every possible solution and it goes in an infinite loop?
Increment the last value by a random amount instead of using a random value. Like so:
$results = mysql_query("SELECT * FROM thetable ORDER BY theId DESC LIMIT 1");
$keyToUse = 1;
if($row = mysql_fetch_array($results)) {
$keyToUse = (int)$row['theId'] + rand(1, 100);
}
Then convert the integer key to and from any format, say using base_convert.
Put your PK through an algorithm that generates a unique number from it and put that through your function.
The best bet would be to make sure the image doesn't exist by using the random number generator against the list of images before writing a new image with that number in it.
Try to increase the amount and type of characters by using an algorithm that uses numbers, letters so it increases the combinations that you can have.
Did you try using mt_rand() http://www.php.net/manual/en/function.mt-rand.php. Also you should be increasing the range.
Use md5 http://php.net/manual/en/function.md5.php
The strings produced have no conflict (with large probability).
i am using $_GET['var'] to get a variable then compare it with a variable in my database. the variable is 1.1 the var is set to "float" on the database so i know it can handle decimals but when i compare them with the code below i get nothing.
include 'connect.php';
$sql=mysql_query("SELECT * FROM table WHERE stuff='$stuff'");
while ($row=mysql_fetch_assoc($sql)) {
$start=$row['start'];
}
echo $start; //nothing happens
From what I know float type isn't precise. It doesn't show you that actual value so 1.1 that you saved may not be the actual value stored. Trying setting your field as decimal and give it a length of say, 10,1 where 10 is the maximum number of digits (the precision) and 1 is the number of digits to the right of the decimal point (the scale). It should work doing query like stuff='1.1' or stuff=1.1.
WHERE stuff = '$stuff' is a String comparison.
Compare number like so
WHERE stuff = $stuff
Don't use float( even if you insert 1.1 into the table, the actual value for float type is not 1.1, but something like 1.100000023841858) . Change it to double in database (or decimal)
You might not be seeing any output because your echo is outside the loop.
The scope of your variable $start would be confined to the loop.
Change the stuff field to DOUBLE type.
Then,
SELECT * FROM table WHERE stuff=$stuff
this should be the sql query