我有一个包含小数值的对象:evo
,meteo
和usage
我尝试用三个条件显示这个值:
(A):Math.round(meteo*100)+Math.round(usage*100) = Math.round(evo*100)
例如,如果我们将A with应用于这些值
{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递增/递减。 我很确定我正在努力做到这一点。
有没有更简单的方法来完成这项任务?
答案 0 :(得分:4)
试试这个:
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...
答案 1 :(得分:1)
如果您希望保持evo
值的准确性而不是根据meteo
和{{的总和计算它,则采用不同的方法1}}。 (这比使用usage
)
查看evo = metro + usage
和meteo
的小数位数,然后根据结果使用usage
或.ceil()
。
.floor()