JavaScript rounding to 1 decimal place on inline style attribute -



JavaScript rounding to 1 decimal place on inline style attribute -

i have function generating random rgba color , if log console rounding on decimal place(that want), if open console , seek inline style attribute on body element can see it's not rounding 1 decimal place ? problem ?

jsfiddle(backgroundcolor)

setinterval(function foo (){ document.body.style.backgroundcolor = ("rgba(" + math.round(math.random() * 255) + "," + math.round(math.random() * 255) + "," + math.round(math.random() * 255) + "," + math.random().tofixed(1)) + ")"; },1000);

jsfiddle(console.log)

js

setinterval(function foo (){ console.log(("rgba(" + math.round(math.random() * 255) + "," + math.round(math.random() * 255) + "," + math.round(math.random() * 255) + "," + math.random().tofixed(1)) + ")"); },1000);

if compare these 2 fiddles can see difference.so why different? same function , should same, right ?

the browser internally stores alpha value 1 byte, not float. when illustration need 0.5 alpha, browser converts 1 byte integer using this:

math.floor(255 * 0.5)

when query result back, wil convert integer 0-1 range dividing 255.

this result in wrong alpha. i've tested using this:

rgba(134,78,73,0.5) //the color outputed javascript rgba(134, 78, 73, 0.498039) //the color read style

0.498039 = math.floor(255 * 0.5) / 255; (of course of study rounding)

javascript

Comments

Popular posts from this blog

assembly - What is the addressing mode for ld, add, and rjmp instructions? -

vowpalwabbit - Interpreting Vowpal Wabbit results: Why are some lines appended by "h"? -

Is there a way to convert an HTML page styled with Bootstrap CSS into email-compatible html? -