Convert negative float to positive in JavaScript
How do I convert a negative float (lik开发者_高级运维e -4.00) to a positive one (like 4.00)?
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
.
Take the absolute value: Math.abs(-4.00)
Do you want to take the absolute value ( Math.abs(x) ) or simply flip the sign ( x * -1.00 )
var f=-4.00;
if(f<0)
f=-f;
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);
value * -1
..is the simplest way to convert from negative to positive
精彩评论