[removed] Display positive numbers with the plus sign

后端 未结 9 1447
既然无缘
既然无缘 2020-12-11 00:05

How would I display positive number such as 3 as +3 and negative numbers such -5 as -5? So, as follows:

1, 2, 3 goes into +1, +2, +3

but if those are

<
相关标签:
9条回答
  • 2020-12-11 00:07

    write a js function to do it for you?

    something like

    var presentInteger = function(toPresent) {
        if (toPresent > 0) return "+" + toPresent;
        else return "" + toPresent;
    }
    

    you could also use the conditional operator:

    var stringed = (toPresent > 0) ? "+" + toPresent : "" + toPresent;
    

    Thanx to the comments for pointing out that "-" + toPresent would put a double -- on the string....

    0 讨论(0)
  • 2020-12-11 00:08
    function format(n) {
        return (n>0?'+':'') + n;
    }
    
    0 讨论(0)
  • 2020-12-11 00:15
    printableNumber = function(n) { return (n > 0) ? "+" + n : n; };
    
    0 讨论(0)
  • 2020-12-11 00:17

    You can use a simple expression like this:

    (n<0?"":"+") + n
    

    The conditional expression results in a plus sign if the number is positive, and an empty string if the number is negative.

    You haven't specified how to handle zero, so I assumed that it would be displayed as +0. If you want to display it as just 0, use the <= operator instead:

    (n<=0?"":"+") + n
    
    0 讨论(0)
  • 2020-12-11 00:18

    something along the lines of:

    if (num > 0)
    {
       numa = "+" + num;
    }
    else
    {
       numa = num.toString();
    }
    

    and then print the string numa.

    0 讨论(0)
  • 2020-12-11 00:22

    Modern syntax solution.

    It also includes a space between sign and number:

    function getNumberWithSign(input) {
      if (input === 0) {
        return "0"
      }
    
      const sign = input < 0 ? '-' : '+';
    
      return `${sign} ${Math.abs(input)}`;
    }
    
    0 讨论(0)
提交回复
热议问题