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

When dividing a floating-point number, you often need to round the result to a specific number of decimal places and handle any remainder. This is useful for financial calculations, splitting costs, or distributing values evenly.

Problem

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

Solution Using toFixed()

The toFixed() method rounds a number to a specified number of decimal places and returns a string. We use the unary plus operator (+) to convert it back to a number.

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 }

How It Works

The function works in these steps:

  1. Calculate the quotient by dividing the number by parts and round to specified precision
  2. Calculate the remainder by subtracting the quotient multiplied by (parts - 1) from the original number
  3. If quotient equals remainder, return equal parts; otherwise return parts with remainder

Alternative Using Math.round()

You can also use Math.round() for rounding to decimal places:

const roundToDecimals = (num, decimals) => {
    const factor = Math.pow(10, decimals);
    return Math.round(num * factor) / factor;
};

const num = 2.74;
const parts = 4;
const quotient = roundToDecimals(num / parts, 2);

console.log("Original number:", num);
console.log("Quotient rounded to 2 decimals:", quotient);
console.log("Remainder:", roundToDecimals(num - quotient * (parts - 1), 2));
Original number: 2.74
Quotient rounded to 2 decimals: 0.69
Remainder: 0.67

Conclusion

Use toFixed() for simple decimal rounding or Math.round() with multiplication/division for more control. Both methods help handle floating-point precision issues in JavaScript calculations.

Updated on: 2026-03-15T23:19:00+05:30

910 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements