假设我们有一个浮点数-
2.74
如果我们将此数字除以4,则结果为0.685。
我们想将此数字除以4,但结果应四舍五入为2个小数。
因此,结果应为-
3 times 0.69 and a remainder of 0.67
为此的代码将是-
const num = 2.74;
const parts = 4;
const divideWithPrecision = (num, parts, precision = 2) => {
const quo = +(num / parts).toFixed(precision);
const remainder = +(num - quo * (parts - 1)).toFixed(precision);
if(quo === remainder){
return {
parts,
value: quo
};
}else{
return {
parts: parts - 1,
value: quo,
remainder
};
};
};
console.log(divideWithPrecision(num, parts));输出结果
控制台中的输出将是-
{ parts: 3, value: 0.69, remainder: 0.67 }