3

How do I convert a negative float (like -4.00) to a positive one (like 4.00)?

6 Answers 6

10

The best way to flip the number is simply to multiply it by -1:

console.log( -4.00 * -1 ); // 4

If you're not sure whether the number is positive or negative, and don't want to do any conditional checks, you could instead retrieve the absolute value with Math.abs():

console.log( Math.abs( 7.25 ) );     // 7.25
console.log( Math.abs( -7.25 ) );    // 7.25
console.log( Math.abs( null )) ;     // 0
console.log( Math.abs( "Hello" ) );  // NaN
console.log( Math.abs( 7.25-10 ) );  // 2.75

Note, this will turn -50.00 into 50 (the decimal places are dropped). If you wish to preserve the precision, you can immediately call toFixed on the result:

console.log( Math.abs( -50.00 ).toFixed( 2 ) ); // '50.00'

Keep in mind that toFixed returns a String, and not a Number. In order to convert it back to a number safely, you can use parseFloat, which will strip-off the precision in some cases, turning '50.00' into 50.

Sign up to request clarification or add additional context in comments.

2 Comments

Good, but in case 50.00 it will lose .00. Sometimes it is important.
If you need the precision, toFixed is always available. Math.abs(-50.00).toFixed(2) will yield the string 50.00.
1

Take the absolute value: Math.abs(-4.00)

Comments

1

Do you want to take the absolute value ( Math.abs(x) ) or simply flip the sign ( x * -1.00 )

Comments

0
var f=-4.00;

if(f<0)
f=-f;

1 Comment

Downvoting, does'nt need those convolutions, Math.abs() does the same thing simpler.
0

If you know the value to be negative (or want to flip the sign), you just use the - operator:

n = -n;

If you want to get the absolute value (i.e. always return positive regardless of the original sign), use the abs method:

n = Math.abs(n);

Comments

-1

value * -1

..is the simplest way to convert from negative to positive

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.