Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript: Display positive numbers with the plus sign

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

like image 467
Soso Avatar asked Dec 03 '10 15:12

Soso


People also ask

How do you make a number positive in JavaScript?

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.

How do you check if a number is positive in JS?

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.

How do you make a positive number negative in JavaScript?

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!

How do you display negative numbers in JavaScript?

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.


2 Answers

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 
like image 50
Guffa Avatar answered Sep 23 '22 06:09

Guffa


// 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.

like image 24
Tom Gullen Avatar answered Sep 21 '22 06:09

Tom Gullen