Reading a float from mySQL - php

I have two float variables that are equal, I retrieve them by PHP and subtract them. the result equals (7.105427357601E-15) I tried to change to double or to decimal and none of that worked. This is what I use in PHP:
$giftcard_balance = $giftcard['balance'];
$total = $product['price'];
$total -= $giftcard_balance;
echo $total;
Here instead of showing 0, it's showing (7.105427357601E-15)
Anyone can help please?

When dealing with prices and account balances you will find that DECIMAL(6, 2) is much easier to deal with than FLOAT. If you experience the same problem when using DECIMAL datatype please post a specific example.
Using round() or similar is a very bad idea as it is simply masking the problem, not fixing it.

In order to get rid of the float inaccuracy, you can, for example, use number formatting.
$a = 7.105427357601E-15;
$b = number_format($a, 2);
echo $a , "\n", $b , "\n";

Perhaps you're looking for the php intval function.
Or maybe the round function.

Related

In PHP number with 19 digit changes in to exponential number

In PHP i have define a variable with 19 digit long number and then print it. But it changes into exponential NUmber which is not acceptable in API Use. I need it as NUMBER. Here is an example of Problem.
$a = 1435483000000072013;
echo $a;
adn it returns 1.4354830000001E+18
Also, I have tried following function but it return wrong number
function output($x) {
$f = sprintf('%0.08f', $x);
$f = rtrim($f,'0');
$f = rtrim($f,'.');
return $f;
}
echo output(1435483000000072013);
this returns me 1435483000000071936 Number changes
So what is solution for this??
Champ, PHP doesn't have strictly typed variables, but it still has to decide whether your number is an int, a float or a double when it stores the information. And your number is larger than INT_MAX, so it's not going to fit into an integer format. That means the system has to bump it up to at least a float, which is where you're getting the exponential format from.
See NoGray's solution for how to fix it. Your number is still being stored, it's just being represented differently because your number is too big.
You can use number_format with an empty string for the thousands separator
e.g.
$a = 1435483000000072013;
echo number_format($a, 0, '.', '');
$a = 1.435483000000072013;
printf("%.18f",$a);

How to remove decimal in PHP?

I am currently echoing a number like this:
<?php echo $enterprise_platinum_price ?>
The problem is that the number normally has a decimal place such as 19.44 or 13.353
I need to display the full number but without the decimal point or any of the numbers behind it. I know that you can round to the full number in PHP but I don't ever want it to round up. If the only way to do this is with rounding, I need it to always round down...
Use the math floor function to round downward.
$a = floor(1.99); // $a = 1
You can also do it without rounding using number_format. There's many, many more ways, but I think the floor() option is the shortest for you.
$a = number_format(1505.99, 0, '', ''); // $a = 1505

PHP - number_format issues

number_format stupidly rounds numbers by default. Is there just a simple way to turn off the rounding? I'm working with randomly generated numbers, and I could get things like...
42533 * .003 = 127.599 or,
42533 * .03 = 1275.99 or,
42533 * .3 = 12759.9
I need number_format (or something else) to express the result in traditional U.S. format (with a comma separating the thousands) and not round the decimal.
Any ideas?
The second argument of number_format is the number of decimals in the number. The easiest way to find that out is probably to treat it as a string (as per this question). Traditional US format is default behaviour, so you don't need to specify remaining arguments.
$num_decimals = strlen(substr(strrchr($number, "."), 1));
$formatted_number = number_format($number, $num_decimals);
If anyone's interested in this, I've written a little function to get around this problem.
With credit to Joel Hinz above, I came up with...
function number_format_with_decimals($value, $round_to){
//$value is the decimal number you want to show with number_format.
//$round_to is the deicimal place value you want to round to.
$round_to_decimals = strlen(substr(strrchr($value, "."), $round_to));
$ans = number_format($value, $round_to);
return $ans;
}
I tried these solutions, but what ended up being my answer was this:
$output=money_format('%!i', $value);
This gives you something like 3,234.90 instead of 3,234 or 3,234.9

Simple math with decimals in PHP

This is killing me! I've never had so much trouble and I can't figure out what I'm doing wrong here.
If I have a number, say 2.32, and I want to do math with it it won't work out. The very simplest example:
$income = $commission; //Commission is 2.32, retrieved from XML
echo "income: $income<br>";
$income100 = $income*100;
echo "income100: $income100<br>";
The result I get is:
income: 2.32
income100: 200
How can I use a decimal number accurately with math without it changing it?
Thanks so much!
You need to assign $income in the following manner to get rid of the underlying SimpleXMLElement:
$income = (float) $commission;
Example of what happens when you don't:
$x = simplexml_load_string("<a>2.4</a>");
echo $x * 100; // output: 200
Besides using floats as Tim said, also make sure to use the BC Math functions when performing arithmetic operation on floating point numbers. Specifically bcmul():
$income100 = bcmul($income, 100);
The problem with floating-point numbers is that you cannot represent decimal numbers with them (unless it can be written as a/b for integer a and b, and even then only if abs(a) < pow(2,52) and b is a power of 2).
You may be better off using string functions to get an integer value:
$tmp = explode(".",$commission);
$tmp = intval($tmp[0].str_pad(substr($tmp[1],0,2),2,"0"));
This will split up the integer part from the decimal part, ensure the decima part is two digits long, and shove it on the end of the integer part, thus effectively multiplying the original number by 100.
I think the easiest solution would be to cast it to a float with floatval()
$income = floatval($comission)
leave the rest of the code as is and it should work as intended.

number format for calculation

When 10000-100, then result should be 9900.
I tried when I use:-
< ?php
$num1 = number_format(round(10000,1),2);
$num2 = number_format(round(100,1),2);
echo $num1 - $num2;
?>
The above result is -90, that made me realize that the number_format function is not applicable in calculations.
Would there be any way that I can convert a value of number_format (obtained from POST from a previous page) back to numerical value for normal calculation?
To start, the reason is that:
(int) "10,000.00"
resolves to 10 since it stops parsing at the first non-numeric character. Thanks to PHP's weird type system, this is done implicitly when you subtract the strings.
Yes, you can strip out the commas easily:
$unformatted = str_replace(",", "", $formatted);
but it's cleaner to just post the raw numeric value (you can still use number_format for the displayed value).
EDIT: It is good practice to explicitly convert numeric strings (without commas) to float (or int) with either a cast ((int) or (float)) or the function version (intval or floatval).
I don't think you can perform this 10,000.00 -100.00 with the comma in the equation. Just perform the raw arithmetic operation then format the answer.
$num1 = 10000;
$num2 = 100;
echo number_format(round($num1 - $num2,1),2);
This outputs
9,900.00
There is an easier way.
number_format is for fomating output numbers or to round easy numbers.
number_format gives us power to make well fomed rounded numbers, for a better user experience.
For calcualtion and saving Numbers in your MYSQL Database use this.
Save your Numbers in MYSQL always as type DECIMAL not FLOAT. There are lots of bugs if you want to calculate with FLOAT fields.
Than use the english notation.
$number = 1234.56;
// english notation without thousands separator
$english_format_number = number_format($number, 2, '.', ''); //
// 1234.57
And now you can calculate and save it, without any Bugs.
Always Remember yourself, Saving numbers into $var is always a string.
Yeah, you can deifine type, but it doesn't matter in first case, and its to long to explain here.
For more information about number_format see here -> http://php.net/manual/en/function.number-format.php

Categories