tags:

views:

110

answers:

3

What would be the preferred way to convert opacity (0 - 1) to hex (00 - ff) in Javascript?

My thoughts are to use an if statement to check if opacity is between 1 and 0.95 then use ff. Work my way down to 0.

+3  A: 

At the most basic level, you're just converting a decimal to hex: How to convert decimal to hex in JavaScript?:

yourNum = yourNum.toString(16);

The 0.0 - 1.0 range is just a percentage format of the 0-255 range. So multiply your value (e.g. 0.5 * 255) then convert to hex, you'll get the correct value.

Rex M
@Anon: Why the dv?
Rex M
@Rex The original version (pre-multiple ninja edits) was incorrect, just pointed to the SO post and had no mention of multiplying by 255
Daniel DiPaolo
I have no Idea why you voted down, I saw some people are very strict to put answer then a reference not a reference only, but a vote down is very exaggerated specially you posted a good answer.
Kronass
[The number one reason to downvote an answer is that it is wrong](http://meta.stackoverflow.com/questions/2451/why-do-you-cast-downvotes-on-answers), which it was. I've since removed the downvote as it has been corrected.
Daniel DiPaolo
Guess I would have found that question if I didn't have opacity stuck in my head.
John Hoover
A: 
  1. Multiply by 255 (this assumes your input range is from 0 to 1 only, and this scales it up to 0-255)
  2. Math.floor()
  3. Convert that decimal number to the hex equivalent
Daniel DiPaolo
+1  A: 

Based on the suggestions of the other answers:

Math.floor(0.0 * 255).toString(16);   // Returns '00'
Math.floor(0.5 * 255).toString(16);   // Returns '75'
Math.floor(1.0 * 255).toString(16);   // Returns 'FF'
Daniel Vassallo