css calc - round down with two decimal cases

前端 未结 3 2077
温柔的废话
温柔的废话 2021-01-17 09:09

I have the following situation:

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

In the context, 100% = 1440px, and <

3条回答
  •  感动是毒
    2021-01-17 09:48

    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.

提交回复
热议问题