segmentio / myth

A CSS preprocessor that acts like a polyfill for future versions of the spec.
4.33k stars 131 forks source link

Calc Inaccurate? #144

Closed JamesCoyle closed 6 years ago

JamesCoyle commented 8 years ago

The following code:

:root {
    --main-width: 67.2rem;
    --aside-width: 33.6rem;
    --nav-width: 22.4rem;
    --total-width: calc(var(--main-width) + var(--aside-width) + var(--nav-width));
}

body {
    max-width: var(--total-width);
}

When 'compiled' produces:

body {
    max-width: 123.20000000000002rem;
}

Rather than the expected:

body {
    max-width: 123.2rem;
}

Is this a floating point error due to Myth or is it a side effect of calc?

thematho commented 8 years ago

The thing is that computers doesn't use decimal numbers rather they calculate floating in binary and they deliver the approximate decimal base float. Please read this article if you really want to understand how it works. It's not a calc error really, but we need to round the result and set the desired precision

JamesCoyle commented 8 years ago

I've programmed for years now and know about floating point errors but I kinda hoped it would be handled more gracefully without adding a bunch of extra characters to the CSS. It's not the best for optimizing download speed if you care about that. I don't use the value much so it's not really a problem but if it was used on a hundred or so different lines it would really start to add up.