3

I have an array which contains this

"postage_cost" => $customer[total_shipping_cost]

when I use var_dump I get

["postage_cost"]=>
  string(5) "34.54"

How can I declare that this is a float and not a string when making the array? I'm sending this array to a web service and I'm afraid there might be some data type confusion. The $customer result is from a MySQL request.

7
  • 3
    On a related note, don't store monetary values in floats due to their inherent imprecision. Commented Feb 19, 2013 at 12:53
  • You may also want to look at using a class with a setter rather than an array. Commented Feb 19, 2013 at 12:55
  • @deceze could you please explain more? the manual of the api says this value should be a float. what is the imprecision? Commented Feb 19, 2013 at 13:01
  • as long as you just convert it before sending to the API, you're okay. But you should not do floating point math with monetary values. Commented Feb 19, 2013 at 13:08
  • 1
    What Every Computer Scientist Should Know About Floating-Point Arithmetic Commented Feb 19, 2013 at 13:10

3 Answers 3

6
"postage_cost" => (float) $customer['total_shipping_cost']

Note that I added quotation marks to the key because i am to 99.999 % sure that you don't have a constant named total_shipping_cost. PHP is gracious about that but with activated error reporting, this would have been a Notice: undefined constant

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, that solved the issue! (as well as all those Notice: undefined constant I was having...)
2
"postage_cost" => $customer['total_shipping_cost'] + 0.0

or

"postage_cost" => (float) $customer['total_shipping_cost']

Beware that I added single quotes around total_shipping_quotes. This is not mandatory but is considered better style than raw text ; it is slightly faster, too.

Comments

1
"postage_cost" => floatval($customer[total_shipping_cost])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.