将浮点数除以 4,四舍五入为 2 个小数点,然后计算 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 }
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP