converting from float to Int in php [duplicate] - php

This question already has an answer here:
explain php output
(1 answer)
Closed 9 years ago.
I am trying to understand converting from a float to an int in PHP ,and came across the following code:
echo (int) ( (0.1+0.7) * 10 ); // echoes 7!
My question is why does it echo 7 instead of 8? What is the logic behind it?

Here:
$var = (int) $othervar;
I would guess:
$var = int($othervar);
would work too. BUT IT DOES NOT!
gettype() will tell you the type, get_class() will tell you the class of an object, both return strings, get_class() returns the current class if no argument or null is provided, if you provide a non-object to get_class() it's some sort of error.
These functions are an example of how bad php, gettype() and get_class(), fun fact, because you have to play "guess which has an underscore" you also have is_a() (function, expects $var and "typename") and instanceof (operator).
Instead it is:
$var = intval($othervar);
and there's floatval, the whole lot have val after them! More PHP sillyness.
Note that:
$var = (string) $othervar;
invokes $othervar's __toString() method, but there isn't a __toInt() method, just strings.
Hope this helps.
Addendum:
Integers are always truncated, hence 7.
Other addendum:
If you want more controlled conversion you can use round() which works as one would expect, floor() (rounds down, so 7 less x less 8 floors to 7, -3 less x less-2 floors to -3) and ceil() which rounds up (7 less x less 8 ceils to 8, -3 less x less -2 ceils to -2)
This question is an almost exact copy of:
Why would on earth PHP convert the result of (int) ((0.1+0.7)*10) to 7, not 8?
Even the example!

Because the actual value stored in memory is something like 7.999999999999999999999999 which is caused by rounding error.

you can also use intval()
$float = 7.99999999999999999999999999999999;
$int = intval($float);
echo $int;

Related

PHP show one decimal place issue [duplicate]

This question already has answers here:
Delete digits after two decimal points, without rounding the value
(15 answers)
Closed 3 years ago.
I'm trying to show one decimal place for rating number I have
but it returns unexpected value.
I used number_format and the round functions and both have the same issue, or i'm doing something wrong.
I tried to make this number show one decimal number
4.96 and it always returns 5 instead of 4.9
number_format(4.96, 1)
round(4.96, 1)
round(4.96, 1,PHP_ROUND_HALF_DOWN)
both functions returns 5 instead of 4.9
I searched all answers but couldn't find anything helpful.
Rounding 4.96 will round .9 up, so it will be 5 in all cases. If you want to do it without rounding, you may have to tweak it a bit to fool it:
floor(4.96 * 10) / 10; // 4.9
Here's a function you can use to achieve this.
function convertToSingleDecimal($num, $precision = 2) {
return floor($num) . substr(str_replace(floor($num), '', $num), 0, $precision + 1);
}
print convertToSingleDecimal("4.96", 1);

Behavior of php function arguments' datatypes [duplicate]

This question already has answers here:
What do strict types do in PHP?
(3 answers)
Closed 3 years ago.
function addition(int $number1, int $number2): int
{
return $number1 + $number2;
}
print('<pre>');
print_r(addition(2, "10"));
print('</pre>');
As a result of above code, it gives me 12. But it should give me an error. Because the second parameter should be an int. But I passed string. Can anyone tell me what kind of behavior happen here?
Thanks in advance.
Declare strict_types(). By default, it is scalar type which is not strict. Also strict_types() has more control over your codes.
declare(strict_types=1);
function addition(int $number1, int $number2): int
{
return $number1 + $number2;
}
IF you are using PHP7, add this:
declare(strict_types = 1);
at the very first line of the script, and than you will get an error.
PHP is loosely typed scripting language and there is no restriction on the variables type and their nature.
$i = "10";
will be considered both integer and the string.
you can read more about this nature by searching about "Why PHP is loosely typed?"

How to convert output of date("Ymd") into a number in PHP? [duplicate]

This question already has answers here:
How do I convert a string to a number in PHP?
(35 answers)
Closed 5 years ago.
I want to have the desired output as such 20170613 which is an integer.
I know using strtotime() I can get an UNIX timestamp as an integer, but I don't want that. date("Ymd") however returns a string.
I can't seem to figure a way to convert this to an integer.
Edit #1: Here is what I am attempting:
$x = (int)date("Ymd");
echo $x;
The result however does not show up in the browser. Infact in the developer's tools, it shows internal server error.
The term to Google is "type cast". That leads you to the PHP type juggling docs on integer casting.
Taking that as a reference point, the canonical way to go about it is:
$int = (int)date('Ymd');
For completeness, you could also use the equivalent full form:
$int = (integer)date('Ymd');
Or the functional:
$int = intval(date('Ymd'));

What's the difference between floatval and (float) in php? [duplicate]

This question already has an answer here:
Typecasting vs function to convert variable type in PHP
(1 answer)
Closed 6 years ago.
I've got some strings that I need to cast as floats but have seen two apparently different ways of doing it:
$float = floatval ($float);
and
$float = (float) $float;
Are there any differences between the two methods?
In all other cases it will be evaluated as a float. In other words, the $string is first interpreted as INT, which cause overflow (The $string value 2968789218 exceeds the maximum value ( PHP_INT_MAX ) of 32-bit PHP, which is 2147483647.), then evaluated to float by (float) or floatval()
Please have look at PHP Convert String into Float/Double
The best answer for this is Typecasting vs function to convert variable type in PHP

PHP function 'pow' weird result [duplicate]

This question already has answers here:
Compare floats in php
(17 answers)
Closed 7 years ago.
I was working on a code and I could not understand the weird result I was getting.
<?php
$a = 0.01;
$p = pow(0.1, 2); // result: 0.01
if( $a < $p ){
echo "true";
}
?>
The result of this condition is always "true" while both of the variables have same value, but the result coming from pow is changing something internally. Seems like I would not be able to rely on this function. Would someone please help me figuring this out ?
its because of float inaccuracy,
take a look at answered question mentioned in comment by b0s3
Read the red warning first
http://www.php.net/manual/en/language.types.float.php. You must never
compare floats for equality. You should use the epsilon technique.
For example:
if (abs($a-$b) < EPSILON) { … } where EPSILON is constant representing
a very small number (you have to define it)
https://stackoverflow.com/a/3149007/4998045
so you can trust pow function but you cant trust float comparsion
PHP Docs said:
base raised to the power of exp. If both arguments are non-negative integers and the result can be represented as an integer, the result will be returned with integer type, otherwise it will be returned as a float.
Maybe you need to convert all to int or all to float.
if( (float)$a < (float)$p ){
echo "true";
}
See it run:
http://phpfiddle.org/main/code/2hv5-n2fw

Categories