PHP check if is integer - php

I have the following calculation:
$this->count = float(44.28)
$multiple = float(0.36)
$calc = $this->count / $multiple;
$calc = 44.28 / 0.36 = 123
Now I want to check if my variable $calc is integer (has decimals) or not.
I tried doing if(is_int()) {} but that doesn't work because $calc = (float)123.
Also tried this-
if($calc == round($calc))
{
die('is integer');
}
else
{
die('is float);
}
but that also doesn't work because it returns in every case 'is float'. In the case above that should'n be true because 123 is the same as 123 after rounding.

Try-
if ((string)(int) $calc === (string)$calc) {
//it is an integer
}else{
//it is a float
}
Demo

As CodeBird pointed out in a comment to the question, floating points can exhibit unexpected behaviour due to precision "errors".
e.g.
<?php
$x = 1.4-0.5;
$z = 0.9;
echo $x, ' ', $z, ' ', $x==$z ? 'yes':'no';
prints on my machine (win8, x64 but 32bit build of php)
0.9 0.9 no
took a while to find a (hopefully correct) example that is a) relevant to this question and b) obvious (I think x / y * y is obvious enough).
again this was tested on a 32bit build on a 64bit windows 8
<?php
$y = 0.01; // some mambojambo here...
for($i=1; $i<31; $i++) { // ... because ...
$y += 0.01; // ... just writing ...
} // ... $y = 0.31000 didn't work
$x = 5.0 / $y;
$x *= $y;
echo 'x=', $x, "\r\n";
var_dump((int)$x==$x);
and the output is
x=5
bool(false)
Depending on what you're trying to achieve it might be necessary to check if the value is within a certain range of an integer (or it might be just a marginalia on the other side of the spectrum ;-) ), e.g.
function is_intval($x, $epsilon = 0.00001) {
$x = abs($x - round($x));
return $x < $epsilon;
};
and you might also take a look at some arbitrary precision library, e.g. the bcmath extension where you can set "the scale of precision".

You can do it using ((int) $var == $var)
$var = 9;
echo ((int) $var == $var) ? 'true' : 'false';
//Will print true;
$var = 9.6;
echo ((int) $var == $var) ? 'true' : 'false';
//Will print false;
Basically you check if the int value of $var equal to $var

round() will return a float. This is because you can set the number of decimals.
You could use a regex:
if(preg_match('~^[0-9]+$~', $calc))
PHP will convert $calc automatically into a string when passing it to preg_match().

You can use number_format() to convert number into correct format and then work like this
$count = (float)(44.28);
$multiple = (float)(0.36);
$calc = $count / $multiple;
//$calc = 44.28 / 0.36 = 123
$calc = number_format($calc, 2, '.', '');
if(($calc) == round($calc))
die("is integer");
else
die("is not integer");
Demo

Ok I guess I'am pretty late to the party but this is a alternative using fmod() which is a modulo operation. I simply store the fraction after the calculation of 2 variables and check if they are > 0 which would imply it is a float.
<?php
class booHoo{
public function __construct($numberUno, $numberDos) {
$this->numberUno= $numberUno;
$this->numberDos= $numberDos;
}
public function compare() {
$fraction = fmod($this->numberUno, $this->numberDos);
if($fraction > 0) {
echo 'is floating point';
} else {
echo 'is Integer';
}
}
}
$check= new booHoo(5, 0.26);
$check->compare();
Eval here
Edit: Reminder Fmod will use a division to compare numbers the whole documentation can be found here

if (empty($calc - (int)$calc))
{
return true; // is int
}else{
return false; // is no int
}

Try this:
//$calc = 123;
$calc = 123.110;
if(ceil($calc) == $calc)
{
die("is integer");
}
else
{
die("is float");
}

you may use the is_int() function at the place of round() function.
if(is_int($calc)) {
die('is integer');
} else {
die('is float);
}
I think it would help you

A more unorthodox way of checking if a float is also an integer:
// ctype returns bool from a string and that is why use strval
$result = ctype_digit(strval($float));

Related

PHP Round decimals always up to the nearest highest decimal

I would like to create a rounding methode to round decimals always up to the closest highest decimal value.
for example: 51.13 => 51.20 or 22.33 => 23.40 but lets say 30.10 stays 30.10
Is this even possible?
Sorry if my explonation is bad but my math english is not the best.
maybe custom function for rounding ?
something like this
$inputNumber=51.13;
function round2deci($number){
$explode = explode(".", $number);
/// 51.13 == 51.ab
$a = substr($explode[1], 0, 1);
$b = substr($explode[1], 1, 2);
// fix for 51.91
if($a == 9){
$explode[0]++;
$a = 0;
$b = 0;
}
if($b > 0){
$a++;
}
echo $explode[0].".".$a."0";
}
round2deci($inputNumber);
and result is :
51.20
I found this answer on the php.net website under the ceil docs that does exactly what you want.
I've added an improved version below which returns a pure float where you'd be able to apply number_format to preserve the trailing zeros of the decimals:
function ceil_dec(float $number, int $precision = 2, string $separator = '.') : float
{
$numberpart = explode($separator, (string)$number);
$numberpart[1] = substr_replace($numberpart[1], $separator, $precision, 0);
if ($numberpart[0] >= 0) {
$numberpart[1] = ceil($numberpart[1]);
} else {
$numberpart[1] = floor($numberpart[1]);
}
$ceil_number = [$numberpart[0], $numberpart[1]];
return (float)implode($separator, $ceil_number);
}
var_dump(
ceil_dec(10.23,1)
);
The above code is good for PHP 7.0 and above, and with declare(strict_types = 1) enabled.

Division by zero warning when divisor is "0.0"

I'm reading data from a text file and performing some basic math. This is how things should work:
// no warning, expected result N/A
$dividend = 100;
$divisor = 0.0;
if (!empty($dividend) && !empty($divisor))
{
$quotient = $dividend/$divisor;
} else {
$quotient = 'N/A';
}
echo $quotient;
This is how things are actually happening.
// yeilds division by zero warning
$dividend = 100;
$divisor = '0.0';
if (!empty($dividend) && !empty($divisor))
{
$quotient = $dividend/$divisor;
} else {
$quotient = 'N/A';
}
echo $quotient;
I'm getting a division by zero warning when a value in the text file is read as '0.0', which empty() sees as non-empty, when it actually empty.
What's the best way to test that '0.0' is actually 0?
Typecast $divisor to float: $divisor = (float)'0.0';
You'll want to cast to float (or use floatval()) in your condition statement. This leaves your values untouched in case you need other data from your variables, such as trailing text:
$dividend = 100;
$divisor = '0.0';
if ((float)$dividend && (float)$divisor) //both are non-zero
{
$quotient = $dividend/$divisor;
} else { //one or the other are zero
$quotient = 'N/A';
}
echo $quotient;
However consider only checking $divisor for zero.
Cast it to an int;
$divisor = (int) '0.0';
i think quotient should be zero if divisior is zero.
So you get a result in the following operations instead a N/A.
I always resolve it like this:
$quotient = ($divisor == 0) ? 0 : ($divident/$divisor);
it should work for "0.0", too.

How I can create my own pow function using PHP?

I want to create a function in which I put two values (value and its power - Example function: multiply(3, 3) result 27). I have tried so far but failed, I have searched using Google but I have been unable to find any result because I don't know the name of this function.
What I want exactly:
3,3 => 3 x 3 x 3 = 27
4,4 => 4 x 4 x 4 x 4 = 256
What I tried:
function multiply($value,$power){
for($x = 1; $x <= $value; $x++ ){
return $c = $value * $power;
}
}
echo multiply(3,3);
The answer has already been accepted, but I had to come here and say that all answers here use a bad algorithm. There are better ones. Including very simple ones, like exponentiation by squaring that reduces the complexity from O(power) to O(log(power)).
The idea is to square the base while dividing the exponent by 2. For example
3^8 = 9^4 = 81^2 = 6561
There is a special case when the exponent is odd. In this case, you must store a separate variable to represent this factor:
2^10 = 4^5 = 16^2 * 4 = 256 * 4 = 1024
PHP isn't one of my strong skills, but the final algorithm is as simple as:
function multiply($value, $power){
$free = 1;
while ($power > 1) {
if ($power % 2 == 1)
$free *= $value;
$value *= $value;
$power >>= 1; //integer divison by 2
}
return $value*$free;
}
echo multiply(3, 3) . "\n";
echo multiply(2, 10) . "\n";
echo multiply(3, 8) . "\n";
Oopsika, couldn't have asked a more obvious question. Use the built-in function named pow (as in a lot of languages)
echo pow(3, 3);
Edit
Let's create our own function.
function raiseToPower($base,$exponent)
{
// multiply the base to itself exponent number of times
$result=1;
for($i=1;$i<=$exponent;$i++)
{
$result = $result * $base;
}
return $result;
}
function exponent($value,$power)
{
$c=1;
for($x = 1; $x <= $power; $x++ )
{
$c = $value * $c;
}
return $c;
}
If you have PHP >= 5.6 you can use the ** operator
$a ** $b Exponentiation Result of raising $a to the $b'th power.
echo 2 ** 3;
If you have PHP < 5.6 you can use pow:
number pow ( number $base , number $exp )
echo pow(2, 3);
Your own function is:
function multiply($value, $power) {
$result = 1;
for($x = 1; $x <= $power; $x++){
$result *= $value;
}
return $result;
}
echo multiply(3,3);
Read more at:
http://php.net/manual/en/language.operators.arithmetic.php
http://php.net/manual/en/function.pow.php
Just try to run this code I hope your problem will be solved.
If you defining any function then you have to call it return value.
<?php
function multiply($value,$exp)
{ $temp=1;
if($exp==0)
return $temp;
else
{
for($i=1;$i<=$exp;$i++)
$temp=$temp*$value;
return $temp;
}
}
echo multiply(5,6);
?>
echo "Enter number (will be mutiplied):".PHP_EOL;
$value = (int) readline("> ");
echo "Enter number for multiplier:".PHP_EOL;
$multiplier = (int) readline("> ");
function power(int $i, int $n):int {
$result =1;
for ($int = 1; $int < $n; $int++){
$result *= $i;
}
return $result;
}
echo power($value,$multiplier);

Rounding up to next significant figure

I need to round up any integer between 1 and infinity in php to the next significant figure (though in practice I'm unlikely to need to round up infinity, so will be happy to settle on reasonable internal limits) eg:
$x <= 10 ? $x = 10
10 < $x <= 100 ? $x = 100
100 < $x <= 1000 ? $x = 1000
etc.
Round / ceil etc don't seem to do the job quite as planned. A pointer towards the correct algorhythm (or function?) would be much appreciated
i think this method will fix your problem:
function n($nr, $p = 10) {
if($nr <= $p) {
return $p;
}
return n($nr, $p*10);
}
heres the result:
echo n(1);
//output 10
echo n(232);
//output 1000
echo n(89289382);
//output 100000000
$x = pow(10,floor(log10($x)) + (floor(log10($x)) == log10($x) && $x!=1 ? 0:1) );
function my_ceil($in) {
if($in == 1) return $in;
if($in == pow(10, strlen($in)-1)) return $in;
return pow(10, strlen($in));
}
echo my_ceil(11); //100
echo my_ceil(10); //10
I think this is what you're looking for:
echo ceil($x / pow(10, strlen($x))) * pow(10, strlen($x));
Only works when $x is an integer, but you say in your question that that is indeed the case, so there's no issue (unless you try to later use it with numbers containing decimals).
This should do the trick:
<?php
function nextSignificantFeature($number){
$upper = pow(10, strlen($number));
return $number == $upper/10 ? $number : $upper;
}
?>
Actually there is the infinity number in PHP, so the implementation should deal with it as you wrote any number from 1 up to infinity Demo:
<?php
function n($number) {
if ($number < 1) {
throw new InvalidArgumentException('Number must be greater or equal 1.');
}
if ($number === INF) {
return INF;
}
$p = 10;
while($number > ($p*=10));
return $p;
}
echo n(1), "\n";
//output 10
echo n(232), "\n";
//output 1000
echo n(89289382), "\n";
//output 100000000
echo n(INF), "\n";
// output INF
echo n(-INF), "\n";
// throws exception 'InvalidArgumentException' with message 'Number must be greater or equal 1.'
This example does the iterative calculation in PHP userland code. There are some math functions in PHP that can do it inline like pow.

PHP: Simple recursive function into iterative function

I was going to do it in C but was confused, so I turned to PHP and was able to copy a recursive function to do this. I am converting an integer into a string with math. Here it is:
function intToString($myDecimal){
if($myDecimal < 10) {
return $myDecimal;
}
return intToString(($myDecimal / 10)) . ($myDecimal % 10);
}
I was able to convert a recursive factorial function before.. but with this I just have no clue.. My attempt is as follows:
function intToStringIter($myDecimal){
$out = "";
while($myDecimal > 10) {
$myDecimal /= 10;
$out .= $myDecimal;
}
$out .= $myDecimal % 10;
return $out;
}
I think I am too tired to see the proper logic at the moment.. It returns 22 instead of 20, I cannot wrap my head around what is correct. Do you see what I am doing wrong?
If you're looking for a conversion to string for big unsigned integers, the code is actually:
function intToString($myDecimal)
{
return sprintf('%u', $myDecimal);
}
If you need to do it with iteration:
function intToString($myDecimal)
{
$result = '';
while ($myDecimal > 9) {
$result = ($myDecimal % 10) . $result;
$myDecimal /= 10;
}
return $myDecimal . $result;
}
UPDATE: My bad, digits were inserted in reversed order. Now it should work. Sorry, untested too.
PHP is not very strict with variables. An integer will become an float if the situation likes it. In your code, $myDecimal /= 10 could make a float of $myDecimal. The following forces $myDecimal to stay an integer. Note: you should pass only integers, if you're passing 9.99, the output would still be 9.99 because 9.99 < 10.
function intToStringIter($myDecimal){
$out = "";
while($myDecimal >= 10) {
$myDecimal = (int) ($myDecimal / 10);
$out .= $myDecimal;
}
$out .= $myDecimal % 10;
return $out;
}

Categories