สมมุติว่าเรามีเลขทศนิยม -
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 }