开发者

CSS opacity defined at 0.3 but set at 0.30000001192092896

I have an <input> element for which I set 开发者_如何学运维opacity: 0.3. However, when I check the actual value I get 0.30000001192092896. See http://jsfiddle.net/85EPf/2/

Why do I get this discrepancy? If this is not a bug, how can I predict the discrepancy for other values?


This is yet another floating-point vs. decimal number rounding issue. See "What Every Computer Scientist Should Know About Floating-Point Arithmetic".

You don't really need to be concerned with the discrepency. Just know that for floating point numbers, you can't express 0.3 exactly. 0.30000001192092896 is close enough.


Floating point numbers represented in binary inside computers are not exact. Your value 0.30000001192092896 is the closest the computer can come to representing 0.3 in binary.


As the others said, this is the result of the fact that floating-point numbers are approximations in JS (and almost all other computer languages.)

If you want to test the opacity against a value, first decide how close is close enough. For example, this tests to see if it's equal to 0.3, within 3 decimal places:

if (300 == Math.round (opactityVal * 1000) ) {
    //-- Do something here.
}

See, also, Minimizing the effect of accuracy problems.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜