dotty
dotty

Reputation: 41433

Convert negative float to positive in JavaScript

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

Upvotes: 3

Views: 7443

Answers (6)

Sampson
Sampson

Reputation: 268344

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.

Upvotes: 10

user239237
user239237

Reputation: 662

value * -1

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

Upvotes: -1

Guffa
Guffa

Reputation: 700262

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);

Upvotes: 0

AlexCuse
AlexCuse

Reputation: 18296

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

Upvotes: 1

Xinus
Xinus

Reputation: 30513

var f=-4.00;

if(f<0)
f=-f;

Upvotes: 0

Darin Dimitrov
Darin Dimitrov

Reputation: 1038730

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

Upvotes: 1

Related Questions