Home > Net >  How to round irrational number using JavaScript?
How to round irrational number using JavaScript?

Time:04-25

I want to divide 1000/3 as an example and set the answer into an input. my problem is that I dont 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

CodePudding user response:

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

CodePudding user response:

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)

CodePudding user response:

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.

CodePudding user response:

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

  • Related