css calc - round down with two decimal cases

Cleiton Souza picture Cleiton Souza · Jun 10, 2016 · Viewed 25.5k times · Source

I have the following situation:

div {
    width: calc((100% / 11) - 9.09px);
}

In the context, 100% = 1440px, and 9.09px is generated in mathematics with sass.

The results is: 94.55px, because calc rounds it up, but I need 94.54px (round down).

How can I round down to the nearest hundredths place?

Edit: example.

Answer

hdante picture hdante · Nov 20, 2020

In general I would say that it's not possible, but there's a hack. However in the web, hacks seem to be the norm, instead of the exception, so I'll just say that it is possible:

div {
    --shf: 4.9406564584124654e-322;
    width: calc(((100% / 11) - 9.09px) * var(--shf) / var(--shf));
}

What this does: it multiplies the value to be rounded by a really small value that underflows the value starting at the third decimal point. Then, it divides the truncated value back, resulting in a rounded version of the value. This assumes that all browsers you support use 64-bit floating point values. If they don't, not only this will be wrong, it might return zero when using smaller floating point data types, completely breaking your page.

Change the exponent to -323 to round at the first decimal point and -324 to round at integer values.