I am getting the currency from google finance using a script and then I am writing the data into a database.
However when I do, I get 9.99999999 instead of what I sent over. I have my InnoDB set to DECIMAL (9,8).
$conn->set_charset('utf8');
$add_currency_query = "INSERT INTO `currency_table`
(`currency_rate`, `time_fetched`, `service`)
VALUES ('$converted_amount', UTC_TIMESTAMP(), 'google-finance')";
And my PHP
$get = explode("<span class=bld>",$get);
$get = explode("</span>",$get[1]);
$converted_amount = preg_replace('/[^0-9\.]/', null, $get[0]);
Any tips on how to fix this/am I doing something wrong?
DECIMAL (9,8) means 9 digits in total and 8 of that after the decimal point.
So what is the max number of that decimal? it is 9.99999999. You get that number when the one you sent is bigger than it is possible to store. MySQL just stores as high as possible when the value overflows.
DECIMAL (9,8) means you have 9 symbols in total, 8 of those are after the dot. This means you can store only numbers up to 9.99999999 if you save anything above it it probably saves as 9.99999999
Suggestion: change your field to be something like DECIMAL (20,8)
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 am working on a financial application. I store decimal to 20 like double(30,20). I am getting strange issue while calculation. I am using Laravel5.2. 3 different result on PHP , Laravel, Excel
Input1 = 280.95000000000000
Input2 = 278.76250000000000
// Results Number_format to 14
$result = Input1 - Input2;
PHP = 2.18750000000000
Laravel = 2.18750000000006
Excel = 2.18749999999994
These three different result effect the final % result. Can anybody know why this is different.
Excel only has precision up to 15 figures (8 bits) https://en.wikipedia.org/wiki/Numeric_precision_in_Microsoft_Excel. Laraval has 15 bits. php has approximately 14 bits http://php.net/manual/en/language.types.float.php
Since many numbers cannot be exactly represented as decimals, errors do creep in. One simple solution is to move the decimal point so that there are only integers.
Input1 = 280.9500000000*10000 -> 2809500
Input2 = 278.7625000000*10000 -> 2787625
result = (Input1-Input2)/10000 -> 21.875
All phone numbers I am trying to enter into my database are being inserted as 2147483647.
The database field is an integer(11).
Before the phone number is inserted, it goes through the following code in order to remove all spaces, dashes, and brackets:
if (!empty($hphone)) $phone = $hphone;
else if (!empty($HomePhone)) $phone = $HomePhone;
else if (!empty($Phone1)) $phone = $Phone1;
$phone = preg_replace("/[^0-9]/", "", $phone);
Why is it inserting the phone number as 2147483647 every time, no matter what the phone number is?
If you can, convert the phone number to a VARCHAR field, don't store it as a signed (or unsigned) numeric value (int, bigint, double, etc...).
In this case, the limit for signed INT in MySQL of 2147483647 is what is causing your issue. Anything larger inserted into this field will be capped at that maximum value.
For example the phone number 555-555-5555 if bigger than that limit (5555555555 >2147483647), as such storing it would result in the max value 2147483647.
I also recommend not storing it as a BIG INT or any other numeric type. How will you handle extension or special encoded characters like:
+02 112020 10020
1-333-232-9393 x203
BTW: don't know if the first is real non-US number format, but you get the idea
Also, phone numbers with relevant leading 0's would be have some of it lost no mater how large the number:
021-392-9293
Would be the number 213929293
if you want to store it as a number use bigint because int has it's max value equal to 2147483647.
So whatever number you try to store that is higher than 2147483647 will be stored as 2147483647.
Here is some reference for mysql types:
http://dev.mysql.com/doc/refman/5.0/en/integer-types.html
I am also facing this type of problem and I have solved that problem after
Updating datatype From 'INT' TO 'BIGINT'.
#php #mysql #database #sql
I've been trawling the web for hours now and trying different methods, and I can't work out why PDO can't insert any row where one of the values contains a decimal.
For example, if the value entered into the cost field has no decimal value then it works fine. But anything like with a decimal and it just ignores the whole row.
200 works, even 200.00 works. But things like 39.99 don't.
Here's the code:
$invoice_id = $db->lastInsertId('id');
$item_name = $_POST['item_name'];
$item_qty = $_POST['item_qty'];
$item_cost = $_POST['item_cost'];
$item_vat = $_POST['item_vat'];
for($i = 0; $i < count($item_name); $i++) {
$item_query = $db->prepare("INSERT INTO hm_invoice_items(invoice, item, qty, amount, vat) VALUES(:invoice, :item, :qty, :amount, :vat)");
$item_query->bindParam(":invoice", $invoice_id);
$item_query->bindParam(":item", $item_name[$i]);
$item_query->bindParam(":qty", $item_qty[$i]);
$item_query->bindParam(":amount", $item_cost[$i]);
$item_query->bindParam(":vat", $item_vat[$i]);
if (!$item_query->execute())
{
die(showMessage("There has been a problem adding the invoice items.", "Error!"));
}
}
A var_dump tells me that the insert query is receiving the values, but it does not like dealing with decimals.
There could be an issue with decimal separator.
When debugging such cases it's essential to var_dump() e-ve-ry-thing!
Why don't you var_dump your values for the closer inspection?
Why didn't you play with decimals only, without POST, without other values?
A question titled "Can't insert decimal value with PDO" should contain short reproduceable code with decimal value present to readers and the result.
Judging by indirect measures will do no help for you and - especially - won't bring you help from strangers.
"var_dump your values" means every suspicious value, like
var_dump($item_cost[$i]);
inside your loop
if you get no output - then there is empty value, so, no wonder nothing inserted.
By the way, you're binding apparently decimal item_cost value to apparently integer amount field. Is it a typo?
But again - where is a certain reproduceable proofcode contains one insert query, one hardcoded decimal value and one result? Ugh - and table definition of course.
Try this?
$item_query->bindParam(":amount", floatval($item_cost[$i]));
At least it works for me when I deal with MySQL decimal data type with PDO.
Use the following to display the content of all the values POSTed to your PHP script:
print_r($_POST);
I'll try and keep this simple. I'm using a BIGINT data type on a MySQL database table. I have a function generating a unique random number that may span anywhere from 12 digits to 13 digest long.
When I insert into the database with a digit that is 12 digits in length, it enters it just fine,
but when I use a value that is 13 digits or longer, it seems like it rounds up or something. here is the
php
$defaultText = 'some string'; //just some string
$web_id = 12;
$element_id = 23112182735363; //case 1 (doesn't work)
//$element_id = 2311218333205; //case 2, does work ()
mysql_query("INSERT INTO tableName (web_id, element_id, content)
VALUES ($web_id, $element_id, '".mysql_real_escape_string($defaultText)."')");
results:
in case one, it inserts a slightly different number, usually rounds up for some reason.
in case two, it inserts the number just fine! Maybe someone can help shed some light on this mystery! Thanks again!
the big int datatype:
bigint(200)
Numbers lose their precision from PHP_INT_MAX onwards. See also: http://www.php.net/manual/en/reserved.constants.php#constant.php-int-max
After that they are turned into floats which have limited precision and causes weird rounding issues. The only way to support BIGINT in PHP is by using strings.
I assumed you were talking about a 32-bit server.
But in my server, PHP seemed not lose the precision.
echo(PHP_INT_MAX . "<br/>");
$big_int = -6174803190685607000;
echo($big_int . '<br/>');
output
9223372036854775807<br/>-6174803190685607000<br/>
Sadly I still got the precision losing. I guessed it might because i used 'i' in prepare statement of mysqli, but I could not prove it.