PHP intval vs floor - php

Is there any difference between floor() and intval()? Though both returns the same results, is there any issue with regard to performance? Which of the two is faster? Which is the right php function to use if I just want to return the whole value only of a decimal?
The goal here is to display 1999.99 to 1999, omitting the decimal value and only return the whole number.
$num = 1999.99;
$formattedNum = number_format($num)."<br>";
echo intval($num) . ' intval' . '<br />';
echo floor($num) . ' floor';

The functions give different results with negative fractions.
echo floor(-0.1); // -1
echo intval(-0.1); // 0

The fastest way is to use type casting: (int)$num.

Per the docs,
The return value of floor() is still of type float because the value range of float is usually bigger than that of integer.
Intval() returns an int, however.

$v = 1999.99;
var_dump(
intval($v),
floor($v)
);
Output:
int(1999)
float(1999)
Docs:
http://php.net/manual/en/function.intval.php
http://php.net/manual/en/function.floor.php

$ratio_x = (0.70/100);
$computation = $ratio_x * 8000;
$noDeci = floor(($ratio_x * 8000)*1)/1;
$intval = intval(($ratio_x * 8000)*1)/1;
$noDeci_hc = floor((int)56*1)/1;
echo $computation."|".$noDeci."|".$noDeci_hc."|".$intval;
OUTPUT:
56|55|56|55
$noDeci returns 55???

Related

PHP round to integer

I want to round a number and I need a proper integer because I want to use it as an array key. The first "solution" that comes to mind is:
$key = (int)round($number)
However, I am unsure if this will always work. As far as I know (int) just truncates any decimals and since round($number) returns a float with theoretically limited precision, is it possible that round($number) returns something like 7.999999... and then $key is 7 instead of 8?
If this problem actually exists (I don't know how to test for it), how can it be solved? Maybe:
$key = (int)(round($number) + 0.0000000000000000001) // number of zeros chosen arbitrarily
Is there a better solution than this?
To round floats properly, you can use:
ceil($number): round up
round($number, 0): round to the nearest integer
floor($number): round down
Those functions return float, but from Niet the Dark Absol comment: "Integers stored within floats are always accurate, up to around 2^51, which is much more than can be stored in an int anyway."
round(), without a precision set always rounds to the nearest whole number. By default, round rounds to zero decimal places.
So:
$int = 8.998988776636;
round($int) //Will always be 9
$int = 8.344473773737377474;
round($int) //will always be 8
So, if your goal is to use this as a key for an array, this should be fine.
You can, of course, use modes and precision to specify exactly how you want round() to behave. See this.
UPDATE
You might actually be more interested in intval:
echo intval(round(4.7)); //returns int 5
echo intval(round(4.3)); // returns int 4
What about simply adding 1/2 before casting to an int?
eg:
$int = (int) ($float + 0.5);
This should give a predictable result.
Integers stored within floats are always accurate, up to around 253, which is much more than can be stored in an int anyway. I am worrying over nothing.
For My Case, I have to make whole number by float or decimal type
number. By these way i solved my problem. Hope It works For You.
$value1 = "46.2";
$value2 = "46.8";
// If we print by round()
echo round( $value1 ); //return float 46.0
echo round( $value2 ); //return float 47.0
// To Get the integer value
echo intval(round( $value1 )); // return int 46
echo intval(round( $value2 )); // return int 47
My solution:
function money_round(float $val, int $precision = 0): float|int
{
$pow = pow(10, $precision);
$result = (float)(intval((string)($val * $pow)) / $pow);
if (str_contains((string)$result, '.')) {
return (float)(intval((string)($val * $pow)) / $pow);
}
else {
return (int)(intval((string)($val * $pow)) / $pow);
}
}
Round to the nearest integer
$key = round($number, 0);

How could i show only one digit after floating point

$f = sprintf ("%.1f",$per);
echo "You hit".$f."
By this code i can show only one digit after floating point.But when my result is 100%,then it shows 100.0%. I want to show 100%. how could i do this????
The easiest way to do this is to cast resulting string into float again after formatting, i.e.:
$f=100.44;
$g=100;
var_dump((float)sprintf('%.1f', $f));//100.4
var_dump((float)sprintf('%.1f', $g));//100
$per = 100;
$f = sprintf ("%.1f",$per);
$rounded = round($f, 1);
echo $rounded;

Error With Using (int) and (double) together to Cut off Decimals

When I am using (int) with (double) some times it is not working correct.
Look At The PHP Code Example:
I Need To LEAVE 2 Decimals And REMOVE Other...
I Know number_format(); function But I Cannot Use It. Because It Is Rounding Number
number_format(24.299,2);
Output: 24.30
I Need: 24.29
<?php
$str="158.2";
echo (double)$str; // Output: 158.2
echo (double)$str*100; // Output: 15820
echo (int)((double)$str*100); // Output: 15819 <-WHY? It Must To Be 15820, Why 15819?
echo ((int)((double)$str*100)/100); // Output: 158.19
?>
I need To leave two decimals in the number and cut other WITHOUT rounding.
Because of floating point precision (see for example this question: PHP - Floating Number Precision), 158.2 * 100 is not exactly 15820 but something like 15819.99999999.
Now (int) is for type conversion, not for rounding, and any digits after the point are cut of.
I need To leave two decimals in the number and cut other WITHOUT rounding.
This is easy:
number_format($str, 2);
Update
number_format does round, so it is a bit more complicated:
bcmul($str,100,0)/100
bcmul multiplies with arbitrary precision, in this case 0. Results:
bcmul(158.2,100,0)/100 == 158.2
bcmul(24.299,100,0)/100 == 24.29
This doesn't answer the question of why that happens (it could be a precision bug), but to solve your problem, try using $foo = sprintf("%.2f", (float)$str);.
Example:
$str = "158.2";
$num = (double)$str;
print sprintf("%.2f", $num);
EDIT: Infact, yes, this is a precision issue. (in C++) by printing 158.2 to 20 decimal places, I get the output of "158.19999999999998863132". This is an inherent problem with floating point/double precision values. You can see the same effect by using echo sprintf("%.20f", $var); in PHP.
First off, PHP is a language that allows you to type juggle. Which means you do not need the (int) or the (double) to do what you're trying to do.
<?php
$str="158.2"; //could also do $str = 158.2
echo $str; // Ouput: 158.2
echo $str * 100; //Output: 15820
echo number_format($str, 2); //Output: 158.20
echo number_format(($str*100)/100, 2); //Output: 158.20
?>
Use the number_format command to format your numbers how you want.
More here
Never cast an unknown fraction to integers, see the manual on http://www.php.net/manual/en/language.types.integer.php.
(int) ( (0.1+0.7) * 10 ); will result in 7, not 8 as one might expect. Casting from float to integer will always round down - and you may also want to check the operator precedence http://php.net/manual/en/language.operators.precedence.php.
Solution: calculate your fraction before you cast it. $fStr = (float) $str; $iStr = (int) $fStr;
Fixed.
function cutDecimals($number,$decimal){
$_str=(string)$number;
if(strpos($_str,".")!==false){
$dotPosition=strpos($_str,".")+1;
$_numCount=strpos($_str,".");
$_decimal=strlen($_str)-$dotPosition;
if($_decimal<$decimal) return (double)$_str;
else return (double)substr($_str,0,$_numCount+$decimal+1);
}else return (double)$_str;
}
echo cutDecimals("158.099909865",2)."<br />";
echo cutDecimals("14.02",2)."<br />";
echo cutDecimals("41.12566",2)."<br />";
echo cutDecimals("1.981",2)."<br />";
echo cutDecimals("0.4111",2)."<br />";
echo cutDecimals("144.2",2)."<br />";
echo cutDecimals("55.000000",2)."<br />";
echo cutDecimals("1456115.499811445121",2)."<br />";
?>

Removing all decimals in PHP

get this from my database:
252.587254564
Well i wanna remove the .587254564 and keep the 252, how can i do that?
What function should i use and can you show me an example?
Greetings
You can do it in PHP:
round($val, 0);
or in your MYSQL statement:
select round(foo_value, 0) value from foo
You can do a simply cast to int.
$var = 252.587254564;
$var = (int)$var; // 252
As Tricker mentioned you can round the value down or you can just cast it to int like so:
$variable = 252.587254564; // this is of type double
$variable = (int)$variable; // this will cast the type from double to int causing it to strip the floating point.
In PHP you would use:
$value = floor($value);
floor: Returns the next lowest integer value by rounding the value down if necessary.
If you wanted to round up it would be:
$value = ceil($value);
ceil: Returns the next highest integer value by rounding the value up if necessary.
You can just cast it to an int:
$new = (int)$old;
Convert the float number to string, and use intval to convert it to integer will give you 1990
intval(("19.90"*100).'')
Before using above answer what is your exact requirement please see bellow example output.
$val = 252.587254564;
echo (int)$val; //252
echo round($val, 0); //253
echo ceil($val); //253
$val = 1234567890123456789.512345;
echo (int)$val; //1234567890123456768
echo round($val, 0);//1.2345678901235E+18
echo ceil($val); //1.2345678901235E+18
$val = 123456789012345678912.512345;
echo (int)$val; //-5670419503621177344
echo round($val, 0);//1.2345678901235E+20
echo ceil($val); //1.2345678901235E+20
you can use echo (int) 252.587254564;
positive number:
round(252.587254564) // 253
floor(252.587254564) // 252
ceil(252.587254564) //252
(int)252.587254564 // 252
intval(252.587254564) // 252
~~252.587254564 // 252
negative number:
round(-252.587254564) // -253
floor(-252.587254564) // -253
ceil(-252.587254564) // -252
(int)-252.587254564 // -252
intval(-252.587254564) // -252
~~-252.587254564 // -252
if you want just remove decimals without round you can use one of above codes except round and floor(for negative number).
But I recommended the last one, it's simpler and faster using prefix ~~
And there is also a not quite advisable method:
strtok($value, ".");
This cuts of the first part until it encounters a dot. The result will be a string, not a PHP integer. While it doesn't affect using the result much, it's not the best option.
I see many answers, but the question is:
"Well i wanna remove the .587254564 and keep the 252, how can i do
that?"
Since the questioner is asking for php, the function in php will be the one for the job.
$newValue = floor($value);
In MySQL you can use:
select floor(field)
or in PHP you can use:
floor($value);

Rounding a number in PHP without converting it to the locale's representation

So, apparently PHP's round() outputs the result as a string formatted according to the current locale settings. round( 10000.326, 1 ) might return "1.000,3", which is fine if you intend to display the result right away, but not that great if you plan to work further with it.
php.net discussion hints that there is no way to stop round() from localizing the output. Is there really no "pure" rounding function in the library that would return an int or a float/double so that the result could be used in arithmetical operations, or is creating your own the only option?
round() doesn't output the result as a string formatted according to the current locale settings: it returns a float... and has no localization.
float round ( float $val [, int $precision = 0 [, int $mode = PHP_ROUND_HALF_UP ]] )
What you do with the result afterwards is more likely to localize it.
Where did you get the impression that round() returned a localized string?
I'm not too much of an expert, but perhaps number_format() might give you what you need? Based on the comments it doesn't appear to use locale, and I know it rounds.
Assuming rounding integers:
floor($value + .5);
And add precision like this (this is one digit):
$digits = 1;
floor($value * pow(10, $digits) + .5) / pow(10, d$igits);
use sprintf like :
$val = sprintf('%.1f', 1000.326);
gives : 1000.3
It's the automatic conversion to a string for output that probably causes the confusion. There's a more direct question about that. An example was helpful for me:
<?php
setlocale(LC_NUMERIC, 'en_US');
echo 1.234; // 1.234
setlocale(LC_NUMERIC, 'et_EE.UTF-8');
echo 1.234; // 1,234
echo number_format( 1.234, 2, '.', '' ); // 1.23
?>
The round function returns a float but the format is localized.
echo round(3.14159, 2);
setlocale(LC_ALL, 'fr_FR');
echo round(3.14159, 2);
This is what the original poster meant.
I suggest:
setlocale(LC_NUMERIC, 'en_US');
That will set the localization for the decimal separator to English (United States) and will be a period.
float round ( float $val [, int $precision = 0 [, int $mode = PHP_ROUND_HALF_UP ]] )
Where are you see string output???
if you want to force it to int you can type cast like this:
$rnum = (int) round( 10000.326, 1 );
not sure if this is what your looking for though.
you can get more info here http://php.net/manual/en/language.types.type-juggling.php
this is what i did to confirm, i am not sure what your trying to achieve exactely
but this might help
$var = (int) "1.000,3";
$var1 = "1.000,3";
if(is_string($var)) print "true";
else print "false";
if(is_int($var)) print "true";
else print "false";
if(is_string($var1)) print "true";
else print "false";
the results are:
false
true
true
please correct me if i am wrong. thanks.

Categories