When i try to add a integer to 3 digit number formed using php number_format() function give right result but when number become 4 digit it give wrong output.
I have tried this. please explain me the reason behind this??
$num1=number_format(1000.5,2);
$num1+=1;
echo $num1;
Output:2
But
$num1=number_format(100.5,2);
$num1+=1;
echo $num1."
";`
Output:101.5
number_format()
returns a string not a number. It is there to format a numeric type (integer, float) to a string with a specific, desired "layout". So what you do is add the number 1
to the string resulting from number_format
, which will try to cast the string back to a number, apparently resulting in 1
for the string cast as well, which gives you 2 total.
tl;dr; Do calculations on numbers only and then do number_format
at the very end to output in a defined format.
$num1 = number_format(1000.5, 2);
var_dump($num1);
// => string(8) "1,000.50"
$num1 += 1;
var_dump($num1);
// => int(2)
Function number_format() returns string.
And that string is type cast to integer when you are adding 1
See Type Juggling
The quickest solution would be using str_replace() on your formatted number. Something like this would do:
(float)str_replace( ',', '', $formatted_number )
By removing the commas from the string and asking for the float value, you'll get a usable number.