user3733831 user3733831 - 3 months ago 6
PHP Question

Floating number subtraction issue in php

I am having a floating number subtraction issue.

This is my code:

$totalEarning = number_format($bsal+$attn+$incen+$tran+$otdpay+$othpay, 2); // 41,256.25
$totalDed = number_format($adv+$stmp+$insu+$nopay+$other+$emplyepf, 2); // 4,436.60
$netSalary = number_format($totalEarning - $totalDed, 2);


But in
$netSalary
have a different output. My expecting result is
36819.65
, but it gives this
37.00
.

Can anybody tell me what is the wrong with my code?

Answer

What @Mark Baker means:

$totalEarning = $bsal+$attn+$incen+$tran+$otdpay+$othpay;
$totalDed     = $adv+$stmp+$insu+$nopay+$other+$emplyepf;  
$netSalary    = $totalEarning - $totalDed;

echo number_format($netSalary, 2);