javascript - How to round smoothly percentage in JS -
i have object containing decimals values : evo
, meteo
, usage
try display values 3 conditions :
- values can positive , negative
- values must displayed percentage without decimals
- (a) must true
(a): math.round(meteo*100)+math.round(usage*100) = math.round(evo*100)
for example, if apply these values
{evo: 0.1466, meteo: 0.1231, usage: 0.0235}
we unvalid percentages :
evo: 15% meteo: 12% usage: 2%
because values rounded, (a) isn't verified. working on getsmooth function adjust rounded values equation (a) verified.
var smooth = getsmooth(math.round(evo*100), math.round(meteo*100), math.round(usage*100); function getsmooth(evo, meteo, usage){ // case need incremente if( math.abs(evo) > math.abs(meteo) + math.abs(usage) ){ // case need incremente usage if( math.abs(meteo) > math.abs(usage) ){ (usage > 0) ? usage++ : usage--; } // case need incremente meteo else{ (meteo > 0) ? meteo++ : meteo--; } } // case need decremente else{ // case need decremente usage if( math.abs(meteo) > math.abs(usage) ){ (usage > 0) ? usage-- : usage++; } // case need decremente meteo else{ (meteo > 0) ? meteo-- : meteo++; } } return { evo: evo, meteo: meteo, usage: usage }; }
my function isn't workind well, , handle +1 incrementation/decrementation. pretty sure doing hard way.
is there easier way achieve task ?
try this:
function getsmooth(meteo, usage) { meteo = math.round(meteo*100); usage = math.round(usage*100); return { evo: (meteo + usage) / 100, meteo: meteo / 100, usage: usage / 100 }; }
to test errors in calculations in evo
separate visualisation logic:
var evo, meteo, usage; // ... // error handling var eps = 1e-4; // float precision epsilon if(math.abs(evo - (meteo + usage)) > eps) { // there's error in evo... } // processing var smooth = getsmooth(meteo, usage); // continue smooth...
Comments
Post a Comment