I have a number like $amount = '1,120.01' and I need to compare with an integer (e.g. if($amount < 300) { do this } }. However for some reasons php sees such numbers (1,120.01 or 300.00 ) to have a lower value so I'm wondering how should I format it.
You can use this Code to Convert string...As from the ABove
https://stackoverflow.com/a/14482490/627868 Ksg Answer.
<?php
$string_number = '1,120.01';
$number = (str_replace(',','',$string_number));
print $number;
?>
You can strip commas from amount and compare like if(((float)str_replace(',','',$amount)) < 300)
You can try
$amount = '1,120.01';
$amount = format($amount);
if ($amount < 300) {
echo $amount, " less than 300", PHP_EOL;
} else {
echo $amount, " grater than 300", PHP_EOL;
}
Output
1120.01 grater than 300
Function Used
function format($number) {
$places = strlen(substr(strrchr($number, "."), 1));
$number = filter_var($number, FILTER_SANITIZE_NUMBER_INT);
return $number / pow(10, $places);
}