1

Possible Duplicate:
How to prefix a positive number with plus sign in PHP

I have code similar to this

$points = -2;
$points = +2;

I want to display them as strings including the - or +. This works fine for the - but not for the +

I have tried this to try to get the positive sign

echo (string)$points;

Any ideas?

Community
  • 1
  • 1
Sean H Jenkins
  • 1,770
  • 3
  • 21
  • 29
  • No this seemed to make the minus sign go as well. – Sean H Jenkins Dec 02 '11 at 17:32
  • And anyway Daniel A White, read the date posted on that question. It was over a year ago. "asked Apr 21 '10 at 11:22" – Sean H Jenkins Dec 02 '11 at 17:35
  • @SeanHJenkins: "Duplicate" simply means "this has been covered in a previous post", not necessarily that *you* have asked this question before. The date is irrelevant. It's not a bad thing, it's meant to be helpful. – Wesley Murch Dec 02 '11 at 17:35

3 Answers3

2

The positive sign is omitted because if a number isn't negative, it's positive.

You'll have to use a function of sorts:

function format_sign($number) {
  $number = int($number);

  if ($number > 0) {
    return "+" . $number;
  } else {
    return $number;
  }
}

And you can use it like this:

$n = -10;

echo format_sign($n);

Nope, I lied. sprintf() seems like a better solution:

function format_sign($number) {
  return sprintf("%+d", $number);
}
Blender
  • 289,723
  • 53
  • 439
  • 496
1

As Kerrek stated, you can use printf, or you can use a ternary statement:

echo ($points > 0 ? '+' . $points : $points);

For using printf, that'd be: printf('%+d', $points);
Using printf means that you can also specify a designated width and number of decimal places as well, which may come in handy if you're trying to get specific formatting.

Mr. Llama
  • 20,202
  • 2
  • 62
  • 115
0

You can use the follwoing:

printf('%+d', $points);

See the exmaples HERE for more explanation.

Christoph Fink
  • 22,727
  • 9
  • 68
  • 113