Search
 
SCRIPT & CODE EXAMPLE
 

PHP

php convert

// This function strip spaces and other characters from a string and return a number.
// It works for integer and float.
// It expect decimal delimiter to be either a '.' or ','
// Note: everything after an eventual 2nd decimal delimiter will be removed.
function stringToNumber($string) {
    // return 0 if the string contains no number at all or is not a string:
    if (!is_string($string) || !preg_match('/d/', $string)) {
        return 0;
    } 

    // Replace all ',' with '.':
    $workingString = str_replace(',', '.', $string);

    // Keep only number and '.':
    $workingString = preg_replace("/[^0-9.]+/", "", $workingString);

    // Split the integer part and the decimal part,
    // (and eventually a third part if there are more 
    //     than 1 decimal delimiter in the string):
    $explodedString = explode('.', $workingString, 3);

    if ($explodedString[0] === '') {
        // No number was present before the first decimal delimiter, 
        // so we assume it was meant to be a 0:
        $explodedString[0] = '0';
    } 

    if (sizeof($explodedString) === 1) {
        // No decimal delimiter was present in the string,
        // create a string representing an integer:
        $workingString = $explodedString[0];
    } else {
        // A decimal delimiter was present,
        // create a string representing a float:
        $workingString = $explodedString[0] . '.' .  $explodedString[1];
    }

    // Create a number from this now non-ambiguous string:
    $number = $workingString * 1;

    return $number;
}
Comment

PREVIOUS NEXT
Code Example
Php :: phpunit assert not false 
Php :: codeigniter abort 404 
Php :: drop column migration laravel 
Php :: show featured image in post wordpress 
Php :: laravel collection isempty 
Php :: bootstrap pagination laravel 
Php :: laravel create coma separated string from query 
Php :: php return function result to variable 
Php :: laravel dump] 
Php :: how to display the site tagline in wordpress 
Php :: check if session is started 
Php :: php code for video upload 
Php :: Primary Termguzzlehttp/guzzle version with laravel-websockek 
Php :: how to named route resource laravel 
Php :: php formData curl 
Php :: stdclass not found laravel 
Php :: how to get a sum of a column in lravel 
Php :: php line break 
Php :: filter child table data from parent laravel eloquent 
Php :: json_deocde 
Php :: login with email and phone laravel 
Php :: phpmyadmin add foreign key 
Php :: pluck laravel 
Php :: where in laravel 
Php :: trim specific character from strin using php 
Php :: laravel faker example 
Php :: wp php get product item attributes name 
Php :: basename in php 
Php :: how to enable pretty url in yii2 
Php :: php italian date 
ADD CONTENT
Topic
Content
Source link
Name
6+6 =