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
-1, -2, -3 then goes into -1, -2, -3
Using the Bitwise Not Operator So, the computer converts the number to binary, takes two's complement, and adds 1 to the number to convert a negative number to a positive. We will use the Bitwise ~ operator to take a two's complement of a number and add 1 to the number.
sign() is a builtin function in JavaScript and is used to know the sign of a number, indicating whether the number specified is negative or positive.
An alternative approach is to use multiply by -1 . To convert a positive number to a negative number, multiply the number by -1 , e.g. 5 * -1 . By multiplying the number by -1 , we flip the number's sign and get back a negative number. Copied!
To use negative numbers, just place a minus (-) character before the number we want to turn into a negative value: let temperature = -42; What we've seen in this section makes up the bulk of how we will actually use numbers.
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
// 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With