3

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

Ry-
  • 218,210
  • 55
  • 464
  • 476
technazi
  • 888
  • 4
  • 21
  • 42

4 Answers4

12

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

value={predictedHours.toFixed(0).replace('-0', '0')}

Or, in general:

value={predictedHours.toFixed(precision).replace(/^-([.0]*)$/, '$1')}
Ry-
  • 218,210
  • 55
  • 464
  • 476
2

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

Jeremy
  • 1,170
  • 9
  • 26
0

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

technazi
  • 888
  • 4
  • 21
  • 42
  • 1
    Not sure what you mean by real decimals, but try with `(-0.0048).toFixed(2)`. – Ry- Oct 25 '19 at 05:23
  • Yeah good point. Is there a way to avoid that by adding any optional characters in regex? – technazi Oct 25 '19 at 15:38
  • `console.log((-0.0048).toFixed(2).replace(/^-0.?0?/, '0'));` would return 00 – technazi Oct 25 '19 at 15:50
  • I mean… I’d use `.replace('-0', '0')`, as seen. `toFixed` isn’t localized and doesn’t produce scientific notation, so it’s quite safe. – Ry- Oct 25 '19 at 17:06
0

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

Saurye
  • 17
  • 2
  • 5