Let's take this line for instance
$amount = $_POST["priceFinal"];
which is essentially equivilant to
$amount = 5000;
I would like to add two zero at the end so if the amount if 5000 its actually 5000000
Now its important to note that it must remain has an integer, where if i do
$amount = "".$_POST["priceFinal"]."00";
it does the work but its a string and needs to remain an integer
just times you amount by how many 0's you need. for example times by 10 gives you 1 extra 0. so just times by 100 to get two extra 0, this keeps it as an interger as opposed to converting it to a sting as php will always try to assume a variable type.
$amount = $_POST["priceFinal"] * 100;
see this link for more information on definition type. Type Juggling
You could use this assuming you are not calculating anything with it.
// see php.net str_pad for more examples.
$amount = str_pad($_POST['priceFinal'], 2 , '0');
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 creating a basic customer management system for an admin panel and need to create a new id number for each new customer but I want it to run off the row id in the DB. I am checking what the last id number is then adding one to it however. The customer id number goes as follows: 000001, 000002, so forth and so on.
In the script below I first test for MAX customer id from table and fetch the associated data, store the customer id into a variable and then add 1 to the variable result. this is where a small portion of the issue begins. The result after adding is a single digit instead of a 6 digit result such as 000003 for example. I get 3 instead. I then add padding in 0's to the end result with str_pad(); so that I can add the additional 5 0's I need to create the customer number.
The big problem begins when I try to add the while statement. I keep getting this:
"Fatal error: Maximum execution time of 30 seconds exceeded in ..."
I am assuming this is because the while statement is somehow creating an endless loop. Any thoughts on what can fix this? I tried it 3 different ways but I keep getting the fatal error when I do the "do... while loop". Thanks
do{
if($result = $dbConnection->query("SELECT MAX(customerId) AS customerId FROM customers")){
$data = $result->fetch_assoc();
$itemId2 = $data['customerId'];
$customerId = $itemId2 + 1;
}
$customerId = str_pad($customerId, 1, '0', STR_PAD_LEFT);
} while(strlen($customerId) < 5);
sprintf('%06d', 1231);
06 means it will be a 6 digit string, it will add 2 leading zeros to 1231.
Can be adjusted for max length.
May want to cast back to integer if it's important.
I'm using the "number_format" function to denote money" attribute in PHP/MySQL.
The attribute itself is stored in my database.
Select account_balance from my_table where login = 'xxxxxx';
$correct_account_balance = number_format($account_balance,
['my_balance'],2); }
In other words : the denotation "2" will add two extra numbers after the decimal point, as follows : 10.00 (for example)
This code works fine............except for one small problem : if the amount after the decimal point has a zero at the end, it does not display!
For example : if the amount is, say, 10 dollars and 35 cents, it displays correctly : 10.35
However, if the amount is 10 dollars, and 30 cents, it displays as : 10.3 (instead of : 10.30 )
The reason is : my program also performs arithmetical operations on the account_balance AFTER I have converted it using the "number_format" function.
For example :
$correct_account_balance -= 0.25 (this will subtract 0.25 each time the program is executed)
This is why, anytime there is a "zero" at the end of the actual amount (like : 10.30), it displays as : 10.3
Is there anyway to get around this? Google doesn't seem to know;
The reason is : my program also performs arithmetical operations on the account_balance AFTER I have converted it using the "number_format" function.
You'll need to re-run number_format after doing the operations on it.
You really shouldn't run it at all until it's ready for display, either, the commas it adds to larger numbers will hugely mess up your calculations. As an example, the following:
<?php
$number = 100000.30;
$number = number_format($number, 2);
$number -= 0.25;
echo number_format($number, 2);
results in the output:
99.75
Which means you've just stolen $99,900.55 from your customers with a type conversion error.
I have two, hopefully basic number questions.
First, I am using the decimal data type on MySQL to show data like speed or height set to one decimal place like this decimal(4,1) My problem is that for numbers with no dp it is still showing .0 - What I get is '309.0' but what I want is '309'. What do I need to change to hide the '.0'?
Second I have an integer data type showing fixed numbers. Many of the numbers are 0 zero but these are getting treated as null and not displaying. How do I force the 0's to display? (I can't make table changes for this because other columns do have zero's that are null values. It is only this one column that needs zeros to display).
For both of these problems PHP is being used to display the results.
EDIT: code I'm using to display results. the top one needs to not show .0 the bottom one needs to show a zero.
Length:</b> %sft' . PHP_EOL, $row2['length'])
Inversions:</b> %s' . PHP_EOL, $row2['inversions'])
I believe a sneaky trick is if you add 0 to the end of your number, it removes the .0000 etc.
example:
$number = 150.00
$number = $number + 0; //should echo 150
$other_number = 150.500;
$other_number += 0; //should echo 150.5
As for the other, you can simply concatenate the zeros since no calculations seem to be needed
To check for the trailing zero, you could use the following to make sure that the float and integer values are the same:
$num = (floatval($num)==intval($num)) ? intval($num) : floatval($num);
and then for the null value, you could use coalesce(yourColumn, 0) as yourColumn to either get your column value if not null or return 0 as the value..
When I send a value to MySQL in PHP like this:
$mysqli->query("update bank set cash = $cash");
It works fine for smaller numbers, but anything 100 trillion or larger yields unexpected results. Sometimes it updates the number in increments of 100, and sometimes not at all.
A prepared statement also has different, but unreliable results once the number gets larger than a couple billion:
$stmt->prepare("update bank set cash = ?");
$stmt->bind_param('i',$new_cash_amt);
$stmt->execute();
Use double quotes.
use or die(mysql_error()); to see you bug.
Stop using mysql* function, will be deprecated soon.
Fix:
$amount = 17;
$mysqli->query("
update player_stats
set cash = cash + $amount
where username = 'cheater2'
") or die(mysql_error());
You're using single quotes, which wont parse a php variable. It's looking for cash=cash+$amount as a string, not a variable holding data.
I'm answering my own question here.
It turns out that when you pass values like this:
$huge_number = 100000000000012345;
echo "The huge_number is: $huge_number";
It will print the following:
The huge_number is: 1.0000000000001E+17
The precise value is lost in this conversion. That is why the value increments in multiples of 100 sometimes, and not at all at other times.
As with the prepared statement, any values larger than a 32bit integer (since I put an 'i' as the type in the bound parameter) will get truncated and altered unexpectedly. I should have passed the new value as a 'd', like so:
$stmt->bind_param('d',$new_cash_amt); //This works correctly