Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

162
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda