technazi
technazi

Reputation: 958

How to avoid negative 0 or -0 values in javascript

I have tried using toString() and the bitwise operator | but I would like to use the precision and string output. As @trincot mentioned, it is caused by the precision value for e.g. -0.45 will result in -0. I have the code here.

typeof predictedHours //number e.g. -0.45
precision = 0
value={predictedHours.toFixed(precision)}
typeof value //string e.g. "-0"

Question - Is there a one liner to convert -0 to 0 in this line - value={predictedHours.toFixed(precision)}?

Upvotes: 8

Views: 8346

Answers (6)

Circuit Breaker
Circuit Breaker

Reputation: 91

This is what worked for me:

let x = -0.00001;
let twoDecimalPlaces = parseFloat(x.toFixed(2)).toFixed(2)
console.log(twoDecimalPlaces)

Upvotes: 0

Ry-
Ry-

Reputation: 224905

I’m not aware of a particularly clean way to do it, but there’s always:

predictedHours.toFixed(0).replace('-0', '0')

Or, in general:

predictedHours.toFixed(precision).replace(/^-([.0]*)$/, '$1')

Upvotes: 15

Preston Software
Preston Software

Reputation: 379

num + 0 is the most performant and fastest way. -0+0 is positive zero. 0+0 is positive zero. negative numbers stay negative, positive numbers stay positive. this just drops the negative zero business if it is not useful.

Upvotes: 11

Jeremy
Jeremy

Reputation: 1568

use Math.abs() to replace a -0 with an absolute number i.e. 0.

Upvotes: 0

Saurye
Saurye

Reputation: 27

You can also do value = +predictedHours.toFixed(precision) || 0 because -0 || 0 is 0

Upvotes: 1

technazi
technazi

Reputation: 958

I think @trincot's suggestion is better so as to avoid any decimals like -0.48.toFixed(2) to be converted to positive. Took me a while to understand the regex. Just a little caveat though: Due to operator precedence negative numbers stay negative with toFixed when enclosed in brackets. Some examples here:

-0.001.toFixed(2).replace(/^-0$/, "0")
//0 '0'

console.log((-0.48).toFixed(0).replace(/^-0$/, '0')); Correct
//-0 '0'

console.log((-0.48).toFixed(2).replace(/^-0$/, '0')); Correct
//-0.48 '-0.48'

console.log(-0.48.toFixed(0).replace(/^-0$/, '0'));
//0 '0'

console.log(-0.48.toFixed(2).replace(/^-0$/, '0'));
//-0.48 '-0.48'

Also have a look at the examples here - toFixed()

Upvotes: 0

Related Questions