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

118
Views
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 answers
Answer question

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 Report

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 Report

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 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!