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!

3
  • (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. Commented Mar 19, 2015 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? Commented Mar 19, 2015 at 17:14
  • .8 is NOT an integer! 0 != "+0.8". Also, 0 NOT > 0. Commented Mar 19, 2015 at 17:23

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

2 Comments

I assume this method will always require numeric string to start either with the + or - signs. Right ?
@Awena Yes. I added a function that will work in any case : with or without a sign before the numeric value
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';
  }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.