简体   繁体   中英

Convert string into float PHP

I have a column in a MySQL table that is a varchar. However the data in the column is representative of a float value. I want to know if there is an easy way to convert the string into a float without loosing the data. The problem is that there are leading zeros's that are complicating things for me.

Sample data:

"100"
"002"
"075"
"0300"
"0135"

Need to convert to:

1.00
0.02
0.75
0.300
0.135 

When I try to convert by multiplying by a decimal the leading zeros are stripped off and 002 become 2.0 instead of 0.02. Complicating things more some of the string values are 3 characters and some are 4 characters.

I am using PHP 5.4.

Thanks for any assistance.

select cast(insert(your_column, 2, 0, '.') as decimal(10, 3))
from your_table

Try this code, it simply do casting. hope it helps.

$Myfloat = (float) $String;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM