javascriptjsxzero

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)}?


Solution

  • 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')