user2267175
user2267175

Reputation: 593

Round to nearest 0.5, Not 0.0

How can you find the nearest nb.5 value?

Excluding .0 values,

Example,

round(1.0) = 1.5
round(1.99) = 1.5
round(2.0) = 2.5

Upvotes: 0

Views: 254

Answers (4)

Naga Sai A
Naga Sai A

Reputation: 10975

To achieve expected result ,use below option using Math.trunc - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/trunc

let round = (val) => Math.trunc(val) + 0.5
console.log(round(1.99))
console.log(round(1))
console.log(round(2))

Upvotes: 0

Dorian Mazur
Dorian Mazur

Reputation: 524

function round(num) {
    return Math.round((num % 10)) + 0.5
}

console.log(round(1));
console.log(round(1.99));
console.log(round(2));

Upvotes: 0

IEatBagels
IEatBagels

Reputation: 843

Math.floor(value) + 0.5 should do it.

Also, you should clarify your specifications... Because the nearest 0.5 value of 2 is 1.5 AND 2.5, they both are at the same "distance".

I understand that your example deals with this scenario by going to the nearest upper 0.5 value, but is this really what you want?

Upvotes: 4

adiga
adiga

Reputation: 35222

You could add 0.5 to the value returned by Math.floor():

const round = (number) => Math.floor(number) + 0.5

console.log(round(1.0))
console.log(round(1.99))
console.log(round(2.0))

Upvotes: 5

Related Questions