Convert percentage to range

495 Views Asked by At

I have the following function to convert this function to percentage. The range of $y$ is $-120$ to $0$, so $-120 = 0\%$ and $0 = 100\%$.

$$percentage = 10^{(y + 160) / 80}$$

How do I go the other way by converting a percentage to the range $-120$ to $0$?

This doesn't quite work

$$y = 80 * log_{10}(percentage) - 160$$

Code to convert range $(-120, 0)$ to percentage

if (y > -120) {
    n = Math.pow(10, ((y + 160) / 80));
    if (n > 100) {
        n = 100;
    }
    if (n < 0) {
        n = 0;
    }
}

Thanks in advance

BT

2

There are 2 best solutions below

3
On BEST ANSWER

Your first stated formula is incorrect: it does not do what you claim it does.

With $y=-120$, your formula gives $$ \mathrm{percentage} = 10^{0.5} =\sqrt{10} \neq 0. $$ So, your formula does NOT convert $-120$ to $0\%$. Instead, it converts it to roughly $3.16\%$. (It does, however, convert $y=0$ to $100\%$, but that's not good enough here.)

Anyway, because this part was wrong, this is why your log formula also fails.

If you just need any way at all to convert these, use something linear. So, $$ \mathrm{percentage} =\frac{5}{6}y+100 $$ in one direction and $$ y=\frac{6}{5}(\mathrm{percentage}-100) $$ in the other.

0
On

You have an issue which is that your mapping is not a bijection between $[-120, 0]$ and $[0, 100]$. So you cannot invert it to convert back our percentage into your initial value.