Considerations
Well, first I'll make some considerations regarding the validation logic implemented in your application, then focus on solving your problem. You'll decide which one is most convenient.
Entry rules.
Every application needs to have input rules. It is such a validation of user inputs, everything that you type is required to enforce validation.
Considering that this value is a user input and your application will need to understand this entry as INT
it will be necessary to validate, not to calculate the string entered.
I strongly recommend you validate this input and do not transform the value to the correct output, so your application processing the value of the user input correctly.
Performance
Force the user to enter the value correctly, for example:
float 0.2
instead of string 0,2
will improve performance of your application.
Well, you will not have to impose a transformation of typecast convertion .
Saving application performance cost.
Good manners
Security is paramount, so will we validate all user input before processing them?
A simple if(is_numeric($string))
on user input can tell him whether the value he is typing is valid for his application to process. So you enforce validation rules in your application.
Resolution
If your application accepts this type of input and needs to convert it to INT
or FLOAT
you can do it in the following ways:
First let's give replace string characters.
$string = str_replace(',', '.', $string);
Then just work with floatval ()
$float_value = floatval( $string );
This will convert the typecast
string to int
Looking like this:
$string = '0,2';
$string = str_replace(',', '.', $string);
$float_value = floatval( $string );
var_dump(floatval($float_value)); // 0.2
var_dump(is_numeric($float_value)); // true
In this way you can process entries such as 0,2
, 0.2
, 2
, -9999
and 2a0
which will be understood as 2