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

117
Vistas
How to round a decimal to the nearest 0.5 (0.5, 1.5, 2.5, 3.5)

I want to round a number to the nearest 0.5. Not every factor of 0.5, just the 0.5s.

For example, 0.5, 1.5, 2.5, -1.5, -2.5. NOT 1, 1.5, 2, 2.5.

I'm confusing myself just explaining it, so here are some examples of expected outputs.

0.678 => 0.5
0.999 => 0.5
1.265 => 1.5
-2.74 => -2.5
-19.2 => -19.5

I have tried the following code with no luck,

let x = 1.296;
let y = Math.round(x);
let z = y + Math.sign(y) * .5; // 1.5 (Correct!)
let x = -2.6;
let y = Math.round(x);
let z = y + Math.sign(y) * .5; // -3.5 (WRONG, should be -2.5)

The code makes sense in my head, but dosen't work for negative numbers. What am I missing that would make this work?

over 4 years ago · Santiago Trujillo
3 Respuestas
Responde la pregunta

0

function getValue (a){
   var lowerNumber = Math.floor(a);
   console.log(lowerNumber +0.5);
}

getValue(0.678);
getValue(0.999);
getValue(1.265);
getValue(-2.74);
getValue(-19.2);

looks like you want lower full number + 0.5 ;

over 4 years ago · Santiago Trujillo Denunciar

0

First, you can round to integer by

let x = 1.296;
let y = Math.round(x);

Then, you can subtract 0.5 first, then round, then add 0.5

let x = 1.296;
let y = Math.round(x-0.5);
let z = y + 0.5;
over 4 years ago · Santiago Trujillo Denunciar

0

You can try this logic:

  • Get the decimal part from number.
  • Check if value is positive or negative. Based on this initialise a factor
    • For positive keep it 1
    • For negative keep it -1
  • Multiply 0.5 with factor and add it to decimal

var data = [ 0.678, -0.678, 0.999, 1.265, -2.74, -19.2 ]

const output = data.map((num) => {
  const decimal = parseInt(num)
  const factor = num < 0 ? -1 : 1;
  return decimal + (0.5 * factor)
})

console.log(output)

over 4 years ago · Santiago Trujillo 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