Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

160
Views
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

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

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

about 4 years ago · Juan Pablo Isaza Report

0

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)

about 4 years ago · Juan Pablo Isaza Report

0

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.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!