There are 2 important points which need to understand about number_format()
- number_format() takes a float as the 1st argument. If string given than convert it in Integer/Float. If found any character in string take the integer part before that character.
- return a number with grouped thousands that means a string.
First check the datatype
$a = 1234; // integer
$a = 1234.00; // float
$a = "1234.00"; // string and we can use it as int/float
$a = "1,234.00"; // string but we can't use as int/float because of comma
In first example
$val = '1,234.00';
echo number_format($val, 2, '.', '');
The type of $val is string. So number_format() takes only the int/float part of string and when found any character trim that number. So taking only 1 and you are getting 1.00.
Let's try with
$val = '12,34.00';
echo number_format($val, 2, '.', '');
$val = '12Z34.00'; // also check with this
echo number_format($val, 2, '.', '');
And you will get the result 12.00 for both.You can also check with
$val = 12,34;
echo number_format($val, 2, '.', '');
And you will get
PHP Parse error: syntax error, unexpected ','
That means it not assuming $val as a string. Lets we check with a string without ',' and we will again use number_format() with converted number.
$val = "1234.00";
echo $first = number_format($val, 2, '.', ',');
echo $second = number_format($first, 2, '.', ',');
the output of above example is:
1,234.00
1.00
So $val work like a float number and in $first we are getting a string number and for $second it is separate again with comma and the output is 1.00. So if you have a string with comma, first you need to remove comma from that string then format that using number_format()
number_format(float $num, . . . )When that string is converted to afloatit is1because it truncates invalid characters and everything after. Seeecho (float)'1,234.00';$val = str_replace(',', '', $val);beforenumber_format().floatit, that just shows what it does.