getting an odd division error with PHP number_format()
my script calculates a number X by dividing two other numbers, A by B.
X=A/B
when i use number_format(A,2) on A before calculating X, i get a very odd number. Actual figures:
1,045.00 / 5 = 0.2
but if i don't use number_format on A before the division, i get the correct answer. Is n开发者_高级运维umber_format somehow making A into a non-number?
1045 / 5 = 209
number_format
should be used only while pretty printing the number. Its return value should not used in calculation as you did.
Example:
If $A = 1045;
then number_format($A,2)
will be 1,045.00
now if you treat 1,045.00
as a number it will be 1
as comma and remaining char will be ignored and 1/2
is 0.5
which you are getting.
You want round(A, 2)
, not number_format()
which is for string representations (hence named "format").
The docs show that number_format returns a string. Have you tried casting the result of number_format() to a numeric type before your mathematical manipulation?
I had similar issues. It could be better if we use number format dec_point and thousand_separator parameters. you could use number_format($number, 2, '.', ''); It will help to remove your thousand separator
number_format
makes it into a string with commas between thousands, and the comma will be confusing the divisor into thinking that's the decimels based on your locale.
精彩评论