Convert negative float to positive in JavaScript
floating-point, javascript
Solution
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`.
Problem
How do I convert a negative float (like -4.00) to a positive one (like 4.00)?