Hay all, is there a PHP function which adds "+" to positive strings?
i.e
function(4) // returns +4
function(1.0) // returns +1.0
function(-1) // returns -1
function(0) // returns +0
Thanks
EDIT: wants to take and return strings.
Hay all, is there a PHP function which adds "+" to positive strings?
i.e
function(4) // returns +4
function(1.0) // returns +1.0
function(-1) // returns -1
function(0) // returns +0
Thanks
EDIT: wants to take and return strings.
Home made function
function make_positive($int){
if($int >= 0){
return "+".$int;
}else{
return $int;
}
}
Does PHP have its own?
EDIT: changed function name.
You could use (s)printf with the following:
$number = sprintf('%+f', $number);
// "-0" => +0.000000
// "1.2" => +1.200000
or
function formatPositive($number)
{
return ($number > 0) ? "+$number" : $number;
// "0" => "0"
// "-0" => "-0"
// "1.2" => "+1.2"
}
or
function formatPositive($number)
{
switch(true) {
case !is_numeric($number): // "Beer" => "NaN"
$number = 'NaN';
break;
case $number == 0: // "-0" = "±0"
$number "±0";
break;
case $number > 0: // "1.23" => "+1.23"
$number = "+$number";
break;
default: // "-1.23" => "-1.23"
break;
}
return "$number";
}
sprintf("%+d", 5); # should give +5
sprintf("%+d", -5); # should give -5
Quick reference: http://www.php.net/sprintf