tags:

views:

77

answers:

4

What is the PHP command that does something similar to intval() but for decimals?

Eg. I have string "33.66" and I want to convert it to decimal value before sending it to MSSQL.

Thanks.

A: 

You could try floatval, but floats are potentially lossy.

You could try running the number through sprintf to get it to a more correct format. The format string %.2f would produce a floating-point-formatted number with two decimal places. Excess places get rounded.

I'm not sure if sprintf will convert the value to a float internally for formatting, so the lossy problem might still exist. That being said, if you're only worrying about two decimal places, you shouldn't need to worry about precision loss.

Charles
Thank you, I am casting it
johnshaddad
+3  A: 

If you mean a float:

$var = floatval("33.66")

Or

$var = (float)"33.66";

If you need the exact precision of a decimal, there is no such type in PHP. There is the Arbitrary Precision Mathematics extension, but it will return strings, so it's only usefull for you when performing calculations.

Wrikken
+4  A: 

How about floatval()?

$f = floatval("33.66");

You can shave a few nanoseconds off of type conversions by using casting instead of a function call. But this is in the realm of micro-optimization, so don't worry about it unless you do millions of these operations per second.

$f = (float) "33.66";

I also recommend learning how to use sscanf() because sometimes it's the most convenient solution.

list($f) = sscanf("33.66", "%f");
Bill Karwin
Thanks! I am going for casting.
johnshaddad
sscanf revives my 8 years old C life xD Thanks again
johnshaddad
A: 

php is a loosely typed language. It doesn't matter if you have

$x = 33.66;

or

$x = "33.66";

sending it to mssql will be the same regardless.

Are you just wanting to make sure it is formatted properly, or is an actual float?

Crayon Violent
Well, it turned out that I had single quotations before closing the double quotation brackets. That was the reason why MSSQL was refusing it xD Thanks for the note.
johnshaddad
And MySQL will do string <-> number conversions, too. This is not always a good idea.
staticsan