Hiding the decimal if .0 and showing zero if an integer - php

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..

Related

PHP: strings automatically converted to float and gives negative numbers

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

calculate value & display negative number ( if applicable )

OK so in the DB table I have 2 cols & values
Lets say
open = 1.23450 & close = 1.23400
now here is the PHP code that I am trying to use for the calculation
$pips = abs($value['close'] - $value['open'])*1;
This should return a value of -0.0005
However it just simply returns value 0 when I echo $pips
If number of digits after the decimal are fixed ( say 5 digits precision)
$pips = abs($value['close']*100000 - $value['open']*100000);
$pips = $pips/100000;
You are using abs() which returns absolute positive value of a number so you need to multiply by "-1" (minus) and as suggested floating points aren't so good in PHP so better calculate the $pips as a whole number first then dividing depending on the number of digits after the point.

adding additional zero to a post

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');

float not working in mysql database

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

MySql decimal type display problem

I store money values in my db table. E.g. I have 2.50. But when I print that value the 0 is always missing so I get 2.5. The db table money field has the following type: decimal(6,2)
any idea how to fix that?
By default PHP echo and print don't print the trailing zeros of a floating point number.
To overcome this you need to use printf as:
$money = 2.50;
printf("%.2f",$money); // prints 2.50
echo $money; // prints 2.5
print $money; // prints 2.5
The format specifier used in printf is "%.2f" what it means is always print atleast two digits after the decimal point and if there are not so many digits use 0. Note that it is atleast two digits not equal to two digits. So if I print 1.234 with that format it will not truncate it to 1.23 but will print 1.234 and if I print 1 it will result in 1.00

Categories