Reputation: 778
I have a component that returns me a value from 0 to 360 degrees, I need to pass that value to units, for example from 0 to 100.
I have the following function but it seems ugly
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;
}
Do you know a more elegant way?
Upvotes: 1
Views: 702
Reputation: 39532
You can divide by 3.6
and use modulus to make this much prettier:
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
Upvotes: 1