I want to convert "-$251" to integer as -251 but i cant find anything on internet. is there any way to convert this string to integer?
the following code is return 0
CodePudding user response:
User filter_var
echo filter_var($str, FILTER_SANITIZE_NUMBER_INT);
CodePudding user response:
The NumberFormatter class can parse this directly.
$num = "-$251";
$fmt = numfmt_create( 'en_US', NumberFormatter::CURRENCY);
$f = numfmt_parse_currency($fmt, $num, $curr);
var_dump($f, $curr);
//float(-251) string(3) "USD"
Demo : https://3v4l.org/QFNTl
CodePudding user response:
First of all, "$-251" does not have an integer equivalent. The str variable you specify must not have a $ sign. The $ sign will not have an integer equivalent. Therefore, the value will return 0.
$str = "$-251";
echo intval($str);
It will return 0. Because $ does not have an integer equivalent. But
$str = "-251";
echo intval($str);
It will return integer -251.
CodePudding user response:
I think it isn´t possible since you have that "$"-character in there which can´t be converted to an int. All the other characters can be interpreted as integers but not "$".