PHP: intval () for decimal places?

What is a PHP command that does something similar to intval () but decimal?

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

Thanks.

+4
source share
4 answers

What about floatval() ?

 $f = floatval("33.66"); 

You can shave a few nanoseconds from type conversions using the casting function instead of calling the function. But this is in the field of micro-optimization, so do not worry about it if you do not do millions of these operations per second.

 $f = (float) "33.66"; 

I also recommend learning how to use sscanf() , because sometimes this is the most convenient solution.

 list($f) = sscanf("33.66", "%f"); 
+10
source

If you mean float:

 $var = floatval("33.66") 

or

 $var = (float)"33.66"; 

If you need accurate decimal precision, there is no such type in PHP. There is an extension of arbitrary precision in mathematics , but it will return strings, so it is only useful for you when performing calculations.

+3
source

You can try floatval , but floats are potentially lost.

You can try running the sprintf number to get it in a more correct format. The format string %.2f will result in a floating-point number with two decimal places. Excess places are rounded.

I'm not sure that sprintf will convert the value to a float inside for formatting, so a loss problem may still exist. In this case, if you are worried about two decimal places, you do not need to worry about the accuracy of losses.

0
source

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

$ x = 33.66;

or

$ x = "33.66";

sending it to mssql will be the same.

Do you just want to make sure that it is formatted correctly or is the actual float?

-1
source

All Articles