w3resource

JavaScript: Convert a positive number to negative number

JavaScript Math: Exercise-29 with Solution

Convert Positive Number to Negative

Write a JavaScript function to convert a positive number to a negative number.

Test Data :
console.log(pos_to_neg(15));
-15

Sample Solution:

JavaScript Code:

// Define a function named pos_to_neg that converts a positive number to its negative equivalent.
function pos_to_neg(num)
{
    // Compute the absolute value of num using Math.abs(), then negate it.
    return -Math.abs(num);
}

// Output the result of converting 15 to its negative equivalent to the console.
console.log(pos_to_neg(15));

Output:

-15

Flowchart:

Flowchart: JavaScript Math- Convert a positive number to negative number

Live Demo:

See the Pen javascript-math-exercise-29 by w3resource (@w3resource) on CodePen.


For more Practice: Solve these Related Problems:

  • Write a JavaScript function that converts a positive number to its negative equivalent by multiplying by -1.
  • Write a JavaScript function that takes any number and returns its negative absolute value, preserving zero as zero.
  • Write a JavaScript function that checks if a number is positive and converts it to negative without using Math.abs.
  • Write a JavaScript function that conditionally converts a number to negative only if it is greater than zero.

Go to:


PREV : Round Integer to Next Multiple of 5.
NEXT : Cast Square Root to Integer.

Improve this sample solution and post your code through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.