除以浮点数,将其四舍五入为两位小数,然后在JavaScript中计算余数
假设我们有一个浮点数-
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 }热门推荐
10 祝女儿简短祝福语大全
11 大学新年祝福语简短创意
12 元旦适合的祝福语简短
13 朋友出远门祝福语简短
14 初六简短的祝福语
15 祝男孩生日祝福语简短
16 同事调离的祝福语简短
17 拜年红包的祝福语简短
18 妈妈生日祝福语简短励志