2

I'd like to know what is the best way to check whether a numeric string is positive or negative.

I am using this answer on S.O but I am not able to determine whether a number with decimals is + or -

For example :

function check_numb($Degree){
  if ( (int)$Degree == $Degree && (int)$Degree > 0 ) {
    return 'Positive';
} else {
    return 'Negative';
  }
}

print check_numb("+2"); // returns Positive
print check_numb("+2.0"); // returns Positive
print check_numb("+2.1"); // returns Negative ??
print check_numb("+0.1"); // returns Negative ??
print check_numb("-0.1"); // returns Negative

It seems when a decimal is added it returns false. How do you properly check for positive strings > +0.XX and negative < -0.XX which 2 decimals..

Thanks!

Community
  • 1
  • 1
Awena
  • 1,002
  • 5
  • 20
  • 43
  • `(int)"+2.1" == 2` and `2 != "+2.1"` - For ALL numbers, if it is < 0 it is negative and if it is > 0 it is positive. – AbraCadaver Mar 19 '15 at 17:08
  • I understand but given a $numb= "+0.8" ; then (int)$numb returns 0 instead of 0.8, it returns negative. how could I return the (int) with decimals, does this sounds logic? – Awena Mar 19 '15 at 17:14
  • `.8` is NOT an integer! `0 != "+0.8"`. Also, `0` NOT `> 0`. – AbraCadaver Mar 19 '15 at 17:23

2 Answers2

3

Considering the given input, why not :

$number = '+2,33122';
$isPositive = $number[0] === '+' ? 'Positive' : 'Negative';
// Positive

$number = '-0,2';
$isPositive = $number[0] === '+' ? 'Positive' : 'Negative';
// Negative

Here is a more generic code, working even if the sign is removed from your input :

function checkPositive ($number) {
   if (!is_numeric(substr($number, 0, 1))) {
       $sign = substr($number, 0, 1);
       return $sign == '+';
   }
   return $number > 0;
} 


$number = '+2,33122';
var_dump(checkPositive($number));
// true

$number = '-2,33122';
var_dump(checkPositive($number));
// false

$number = '2,22';
var_dump(checkPositive($number));
// true
Clément Malet
  • 5,062
  • 3
  • 29
  • 48
2

Your problem is because: (int)"+2.1" == 2 and 2 != "+2.1". For ALL numbers, if it is < 0 it is negative and if it is > 0 it is positive. If it is == 0, then it is obviously 0 which is unsigned.

function check_numb($Degree){
  if ( $Degree > 0 ) {
    return 'Positive';
} elseif( $Degree < 0 ) {
    return 'Negative';
  }
}
AbraCadaver
  • 78,200
  • 7
  • 66
  • 87