This article was originally published on my personal website here. There's some other react/typescript related content there as well if you want to have a look.
We do have calls like Math.round
or Math.floor
, but those round to full numbers. The first rounds to a full number and the second simply rounds down. What do you do if you need to specify to how many decimal places, or specifically, to which step you want to round?. Well, look no further. I present drumroll The Last Rounding Funciton You Will Ever need
function round(value, step) {
step || (step = 1.0);
const inv = 1.0 / step;
return Math.round(value * inv) / inv;
}
courtesy of Michael Deal.
I supposed you could improve it by also employing EPSILON, but I find that this suffices for the time being.
Top comments (0)