Mojtaba Sedighi
Mojtaba Sedighi

Reputation: 127

How to round rational numbers using JavaScript?

I want to divide 1000/3 as an example and set the answer into an input. my problem is that I don't want them to be float , so I rounded the like this

 const answer =  Math.round(1000/3);

When I set them in 3 inputs all are 333 and the answer of their sum is 999 but I want one of them to be 334 and the others 333 How can I handle that generally? Thanks for your help

Upvotes: 2

Views: 428

Answers (5)

Robert Eisele
Robert Eisele

Reputation: 115

If you want a general solution, you could come up with something like this:

function exactSplit(x, n) { // split x across n slots
   let ret = [];
   let t = Math.round(x / n);
   for (let i = 1; i < n; i++) {
      ret.push(t);
   }
   ret.push(x - (n - 1) * t);
   return ret;
}

exactSplit(1000, 3); // [333, 333, 334]

Upvotes: 0

Pouya M
Pouya M

Reputation: 383

By making a general function, you can achive what you want.

function getRes(num, divide) {
    let answer = Math.round(num / divide);
    let res = num - answer * divide;
    return [answer, res];
}

let num = 1000;
let divide = 7;
let [answer, res] = getRes(num, divide);

let finalAnswer = Array(divide).fill(answer);
finalAnswer[finalAnswer.length - 1] = answer + res;
console.log(finalAnswer);

Upvotes: 1

rand&#39;Chris
rand&#39;Chris

Reputation: 1330

i want one of them to be 334 and the others 333 how can I handle that generally?

How general? I'm not sure there's a perfect answer. However, based on your example, I'd use something like the following:

var input = 1000
var divisors = 3
var value = Math.round(input/divisors)
var display1 = value
var display2 = value
var display3 = input - value * (divisors-1)

console.log( display1, display2, display3 )

In certain circumstances you may need to be more careful with the rounding, but for integer ranges from 0-100 this should be fine.

Upvotes: 1

Anurag Srivastava
Anurag Srivastava

Reputation: 14423

Here's a generic function that will split your integer k into n parts whose sum is k:

const arr = []
, splitInteger = (num, parts) => {
    let sum = 0;
    for (let i = 0; i < parts - 1; i++) {
        const curr = Math.floor(num/parts)
        arr.push(curr)
        sum += curr
    }
    arr.push(num - sum)
}

// Splitting 1000 into 3 parts
splitInteger(1000, 3)
console.log(arr)

// Let's try 7 parts
arr.length = 0
splitInteger(1000, 7)
console.log(arr)

Upvotes: 1

TAHER El Mehdi
TAHER El Mehdi

Reputation: 9213

i want one of them to be 334 and the others 333

Just add one to 1000 to be 1001 so:

let s1 = Math.round(1000/3); //333
let s2 = Math.round(1000/3); //333
let s3 = Math.round(1000/3); //333
console.log(s1+s2+s3); //999
let s4 = Math.round(1001/3); //334
console.log(s2+s3+s4); //1000

Upvotes: 1

Related Questions