tags:

views:

122

answers:

3

I'm in a strange situation where I have a value of 0.5 and I want to convert the values from 0.5 to 1 to be a percentage and from 0.5 to 0 to be a negative percentage.

As it says in the title 0.4 should be -20%, 0.3 should be -40% and 0.1 should be -80%.

I'm sure this is a simple problem, but my mind is just refusing to figure it out :)

Can anyone help? :)

+10  A: 

What we want to do is to scale the range (0; 1) to (-100; 100):

percentage = (value - 0.5) * 200;

The subtraction transforms the value so that it's in the range (-0.5; 0.5), and the multiplication scales it to the range of (-100; 100).

Matti Virkkunen
You know what... I actually had that :) I was using it and for some reason my mind told me it was wrong. I knew it would be something easy. Thanks for the quick response :)
Micheal
+1 because it's the only answer with 2 operations... though I kind of hoped the compiler would optimize the `/ 0.5 * 100` from Mark, I am not so sure :p
Matthieu M.
Many CPUs have a "Multiply and Add" instruction, but no "Add and Multiply" so to me it's more natural to write `(value*200.0) - 100.0`.
MSalters
A: 

Normalize it, and you're done:

// Assuming x is in the range (0,1)
x *= 2.0; // x is in the range (0,2)
x -= 1.0; // (-1,1)
x *= 100; // (-100,100)
greyfade
+1  A: 
percent = ((value - 0.5) / 0.5) * 100

This will generate from -100 to 100. You want to subtract your zero value (0.5) from the given value, and divide by the range that should give 100% (also 0.5 in your example). Then multiply by 100 to convert to percentage.

Mark Ransom