简体   繁体   中英

Convert degrees value to units from 0 to 100

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM