views:

41

answers:

4

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 number_format somehow making A into a non-number?

1045 / 5 = 209

+1  A: 

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.

codaddict
thanks for that clear answer and suggestion
Phil
A: 

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.

Fanis
A: 

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?

Inkspeak
+1  A: 

You want round(A, 2), not number_format() which is for string representations (hence named "format").

Archimedix
thank you for that answer as well
Phil