I am writing a program to sum the digits of a number , it is working fine for small numbers but for large no it is giving unexpected sum? below is the program.
<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);
class demo {
private $sum = 0;
private $num = 0;
private $rem = 0;
public function digit_sum($digit) {
//echo gettype($digit).'<br>';
try {
if (gettype($digit) == 'string') {
throw new Exception($digit . ' is not a valid number <br>');
} else {
$this->num = $digit;
while ($this->num > 0) {
$this->rem = $this->num % 10;
$this->sum = $this->sum + $this->rem;
$this->num = $this->num / 10;
}
return "Sum of no $digit is = " . $this->sum . '<br>';
}
} catch (Exception $e) {
echo $e->getMessage();
}
}
}
$sum = new demo();
echo $sum->digit_sum('sfsdfsdfds');
echo $sum->digit_sum(12345);
// outputs correct sum
echo $sum->digit_sum(3253435674);
//outputs incorrect sum
i see the above code results fine for integer no but not for double no' please guide me what will be the perfect solution to this problem?