Thursday, 12 September 2013

PHP: Convert string to float or get float number from string

(float) function that is the fastest way and the fastest performance to convert a string to a float number.
For example :

echo (float) '154.256';                     // output 154.256
echo (float) '154.256dsgaddgvgf';    // output 154.256
echo (float) '154.256fsadfdsfa15';   // output 154.256
echo (float) 'fsdfdsafd154.256';       // output 0

* if you want to get a float from all numeric characters in string you can try following functions :

function getFloatFromString($string) {
     return (float) preg_replace('/[^0-9.]/', '', $string);
}

example :

echo getFloatFromString('abcdef152.685');       // output 152.685
echo getFloatFromString('abcdef152.6cs85');    // output 152.685
echo getFloatFromString('abcdef152.685fd');    // output 152.685

2 comments:

  1. Infycle Technologies, the No.1 software training institute in Chennai> offers the No.1 Data Science course in Chennai for tech professionals and students at the best offers. In addition to the Data Science course, other in-demand courses such as Python, Selenium, Oracle, Java, Python, Power BI, Digital Marketing also will be trained with 100% practical classes. After the completion of training, the trainees will be sent for placement interviews in the top MNC's. Call 7504633633 to get more info and a free demo.

    ReplyDelete
  2. Infycle Technologies, the best software training institute in Chennai offers the leading Data Science course in Chennai for tech professionals, freshers, and students at the best offers. In addition to the Data Science course, other in-demand courses such as Python, Cyber Security, Selenium, Oracle, Java, Power BI, Digital Marketing also will be trained with 100% practical classes. After the completion of training, the trainees will be sent for placement interviews in the top MNC's. Call 7504633633 to get more info and a free demo.

    ReplyDelete