[removed] Display positive numbers with the plus sign

后端 未结 9 1448
既然无缘
既然无缘 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:31
    // Forces signing on a number, returned as a string
    function getNumber(theNumber)
    {
        if(theNumber > 0){
            return "+" + theNumber;
        }else{
            return theNumber.toString();
        }
    }
    

    This will do it for you.

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

    Even though using ternary operator is arguably more practical, here's another interesting way of doing this:

    '+'.repeat(number >= 0) + number
    

    or this:

    [['+'][number & 0x80000000], number].join('')
    
    0 讨论(0)
  • 2020-12-11 00:34
    ['','+'][+(num > 0)] + num
    

    or

    ['','+'][Number(num > 0)] + num
    

    It is a shorter form than the ternary operator, based on casting boolean to the number 0 or 1 and using it as an index of an array with prefixes, for a number greater than 0 the prefix '+' is used

    0 讨论(0)
提交回复
热议问题