我有一个包含小数值的对象:evo
、meteo
和 usage
我尝试在三个条件下显示此值:
- 值可以是正数也可以是负数
- 值必须显示为不带任何小数的百分比
- (A) 必须为真
(A): Math.round(meteo*100)+Math.round(usage*100) = Math.round(evo*100)
例如,如果我们将 A 应用于这些值
{evo: 0.1466, meteo: 0.1231, usage: 0.0235}
我们将得到无效的百分比:
evo: 15%
meteo: 12%
usage: 2%
因为值是四舍五入的,所以有时 (A) 未被验证。 我正在研究 getSmooth 函数来调整舍入值以使等式 (A) 始终得到验证。
var smooth = getSmooth(Math.round(evo*100), Math.round(meteo*100), Math.round(usage*100);
function getSmooth(evo, meteo, usage){
// case we need to incremente something
if( Math.abs(evo) > Math.abs(meteo) + Math.abs(usage) ){
// case we need to incremente usage
if( Math.abs(meteo) > Math.abs(usage) ){
(usage > 0) ? usage++ : usage--;
}
// case we need to incremente meteo
else{
(meteo > 0) ? meteo++ : meteo--;
}
}
// case we need to decremente something
else{
// case we need to decremente usage
if( Math.abs(meteo) > Math.abs(usage) ){
(usage > 0) ? usage-- : usage++;
}
// case we need to decremente meteo
else{
(meteo > 0) ? meteo-- : meteo++;
}
}
return {
evo: evo,
meteo: meteo,
usage: usage
};
}
我的函数工作不正常,它只处理 +1 递增/递减。 我很确定我正在以艰难的方式做到这一点。
是否有更简单的方法来完成该任务?
最佳答案
试试这个:
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
};
}
在 evo
中独立于您的可视化逻辑来测试计算中的错误:
var evo, meteo, usage;
// ...
// do the error handling
var eps = 1e-4; // some float precision epsilon
if(Math.abs(evo - (meteo + usage)) > eps) {
// there's an error in evo...
}
// now do the processing
var smooth = getSmooth(meteo, usage);
// continue with smooth...
关于javascript - 如何在 JS 中平滑地舍入百分比,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30645911/