Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 518
technazi Avatar asked May 06 '26 23:05

technazi


2 Answers

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.

like image 198
Preston Software Avatar answered May 09 '26 13:05

Preston Software


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')
like image 36
3 revsRy- Avatar answered May 09 '26 11:05

3 revsRy-



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!