That certainly does not work in every case.
dpi.lv detects my 16" Macbook Pro as 3584x2240. Real resolution unscaled 3072 x 1920 (you can't even use that resolution, max apple allow is 2048x1280 - so it looks sharper/retina). I am using 1536x960, otherwise, the image is too small.
Also, my external monitor, which is 4K, is being detected as 6K (6016x3384). Perhaps because I scaled the 4K image to 3K (3008x1692) so text is sharper and not too small, so it's detecting twice as that?
Same thing for the Mac screen. It's detecting double my resolution.
I've run your formula and I think I found out why. Apple seems to be correcting the
screen.width
to the correct value. I get 1792
which is my correct width. window.devicePixelRatio is 2, so thus why I get 3584x2240 (twice of what I have)
I hear your complain, but I think the only way to play with websites is doing what apple is doing. Correcting screen.width and screen.height depending on how you scale your monitor. And the fact that it breaks for all apple hardware, is also a clue that this can't be used and apple seems to be correctly informing proper width, height and devicePixelRatio.