DEV Community

loading...

Discussion on: Identifying Negative Zero

Collapse
egeriis profile image
Ronni Egeriis Persson

A while back I had an interesting use case for -0. I was looking for a way to map x,y coordinates into absolute positioning of an element in CSS. And I wanted that behavior to be different for positive and negative numbers, to create an easy interface for the consumer of that component. So negative x would position the element from the right edge, positive x would position from the left edge. Vice versa for the y axis.

I ended up writing a small function that would determine if the number provided is negative, including -0:

const isNeg = v => v < 0 || 1 / v === -Infinity;

And this function was used to position the element with some simple logic:

const x = `${isNeg(left) ? 'right' : 'left'} ${Math.abs(left)}rem`;
const y = `${isNeg(top) ? 'bottom' : 'top'} ${Math.abs(top)}rem`;