简体   繁体   中英

PHP: sprintf - zero without plus sign

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM