Home > other >  Calculate interest per day correctly
Calculate interest per day correctly

Time:06-13

In this code I am calculating total interest and calculating it per day. But the value I am getting for the interest per day is wrong. The results outputs 0.0027397 instead of 3.317.

$startdate = strtotime('2022-06-06');
$enddate = strtotime('2023-06-06');
$rate = 23.4;
$amount = 5798;
$days = (($enddate - $startdate) / 60 / 60 / 24);
                                                    
$years = number_format((int)$days / 365, 4);
$interest = number_format($amount * ($rate) * $years / 100, 2);
$interestperday = (int)($interest) / (int)($days);
                    
$currentdate = date('Y/m/d');
$datedifference = (int)((strtotime($currentdate) - $startdate) / 60 / 60 / 24);

$finalinterest = $datedifference * $interestperday;

CodePudding user response:

number_format returns a string. And therefore you cannot do mathematical operations on string. Use round instead.

$startdate = strtotime('2022-06-06');
$enddate = strtotime('2023-06-06');
$rate = 23.4;
$amount = 5798;
$days = (($enddate - $startdate) / 60 / 60 / 24);

$years = round((int)$days / 365, 4);
$interest = round($amount * ($rate) * $years / 100, 2);
$interestperday = (int)($interest) / (int)($days);
$currentdate = date('Y/m/d');
$datedifference = (int)((strtotime($currentdate) - $startdate) / 60 / 60 / 24);
$finalinterest = $datedifference * $interestperday;
echo $interestperday;

See it in action: https://onlinephp.io/c/327a0

CodePudding user response:

because it returns a string run number_format on the result instead (your result might be more precise if you run it in the end instead)

$startdate = strtotime('2022-06-06');
$enddate = strtotime('2023-06-06');
$rate = 23.4;
$amount = 5798;
$days = (($enddate - $startdate) / 60 / 60 / 24);

$years = $days / 365;
$interest = $amount * ($rate) * $years / 100;
$interestperday = $interest / $days;
print(number_format($interestperday,2));


$currentdate = date('Y/m/d');
$datedifference = (int)((strtotime($currentdate) - $startdate) / 60 / 60 / 24);

$finalinterest = $datedifference * $interestperday;

$finalinterest = number_format($finalinterest,2);
print($finalinterest);
  •  Tags:  
  • php
  • Related