-1

I'm trying to get minus sign before negative numbers and plus sign before positive ones. I'm using sprintf.

sprintf("%+d",$voteCount)

This is working okay, except for zero. I don't want a plus sign before zero. How can I get it to display plus sign for all positive numbers, but no sign for zero?

Azamat
  • 139
  • 4
  • 14

1 Answers1

2

There is no direct way to achieve this, as %d will consider only positive and negative sign for whatever comes to it.

But yes, there is alternative way to achieve this as follows,

echo ($voteCount === 0 ? 0 : sprintf("%+d",$voteCount));

This should solve your problem.

EDIT(As suggested by AliveToDie) :

You can do the same by using gmp_sign.

Here is reference example of it.

// positive
echo gmp_sign("500") . "\n";

// negative
echo gmp_sign("-500") . "\n";

// zero
echo gmp_sign("0") . "\n";

For the same, you need to enable extension in php.ini

extension=php_gmp.so
Rahul
  • 18,271
  • 7
  • 41
  • 60