Dividing a floating number, rounding it to 2 decimals, and calculating the remainder in JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

Suppose, we have a floating-point number −

2.74

If we divide this number by 4, the result is 0.685.

We want to divide this number by 4 but the result should be rounded to 2 decimals.

Therefore, the result should be −

3 times 0.69 and a remainder of 0.67

Example

The code for this will be −

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));

Output

And the output in the console will be −

{ parts: 3, value: 0.69, remainder: 0.67 }
raja
Published on 20-Nov-2020 14:25:50
Advertisements