Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

167
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda