2014-02-15 25 views
1

我有一個返回我從0到360度的值的部件,我需要通過該值單元,例如從0到100度值轉換爲單元從0到100

我有以下功能但看起來很難看

function degToValue(deg) 
{ 
    var unit = Math.ceil((deg * 100)/360); 
    if (unit === 0) unit = 100; 
    if (deg < 1.6 && deg > 0) unit = 0; 
    return unit; 
} 

你知道更優雅的方式嗎?

+3

http://codereview.stackexchange.com/ – j08691

+0

也被稱爲 「編入格拉提安」:HTTP://en.wikipedia。 org/wiki/Gradian – duffymo

+1

除了Gradian會是0到400,而不是100. – Teepeemm

回答

1

您可以通過3.6和使用模數劃分,使這個漂亮得多:

function degToValue(deg) 
{ 
    var unit = (deg/3.6) % 100; 
    return (unit === 0 ? 100 : unit); 
} 

console.log(degToValue(360)); //100 
console.log(degToValue(0)); //100 
console.log(degToValue(355)); //98.61 
console.log(degToValue(719)); //99.72 
+0

感謝您的回答,但這種方式從不顯示0值。 – eledgaar

+0

@eledgaar什麼時候該顯示0? – h2ooooooo

+0

這是問題所在。相同的度數值不能有兩個不同的值。因此,我的醜陋的條件。無論如何,你的方法更漂亮! – eledgaar