Jeff Voss
Jeff Voss

Reputation: 3695

Round number to nearest .5 decimal

I'm looking for an output of

4.658227848101266 = 4.5

4.052117263843648 = 4.0

the closest I've gotten is

rating = (Math.round(rating * 4) / 4).toFixed(1)

but with this the number 4.658227848101266 = 4.8???

Upvotes: 30

Views: 21243

Answers (7)

Oliver Saer
Oliver Saer

Reputation: 76

Late to this party, but I thought I would throw in a nice answer using a syntax I saw elsewhere, just in case someone comes across this in the future.

const roundDown = decimalNumber => {
  return decimalNumber % 1 >= 0.5 ? +`${~~decimalNumber}.5` : ~~decimalNumber;
} 

Explanation:

  • decimalNumber % 1 leaves you with only the decimal places
  • The + converts the string representation of your constructed number into a float, for consistency
  • ~~decimalNumber drops the decimal places, leaving you with an integer

Upvotes: 0

Faust Legend
Faust Legend

Reputation: 1

This is kinda late. But for someone who wants to round down to whole number or 0.5, you can try this:

function roundDown(number) {
      var decimalPart = number % 1;
      if (decimalPart < 0.5)
         return number - decimalPart;
      else
         return number - decimalPart + 0.5;}

Upvotes: 0

Dave
Dave

Reputation: 3658

(Math.round(rating * 2) / 2).toFixed(1)

Upvotes: 46

mr haven
mr haven

Reputation: 1644

So this answer helped me. Here is a little bit o magic added to it to handle rounding to .5 or integer. Notice that the *2 and /2 is switched to /.5 and *.5 compared to every other answer.

/*
* @param {Number} n - pass in any number
* @param {Number} scale - either pass in .5 or 1
*/
var superCoolRound = function(n,scale) {
    return (Math.round(n / scale) * scale).toFixed(1);
};

Upvotes: 4

cardern
cardern

Reputation: 725

This works for me! (Using the closest possible format to yours)

   rating = (Math.round(rating * 2) / 2).toFixed(1)

Upvotes: 11

Ignacio A. Rivas
Ignacio A. Rivas

Reputation: 636

It's rather simple, you should multiply that number by 2, then round it and then divide it by 2:

var roundHalf = function(n) {
    return (Math.round(n*2)/2).toFixed(1);
};

Upvotes: 25

Thomas
Thomas

Reputation: 12009

I assume you want to format the number for output and not truncate the precision. In that case, use a DecimalFormat. For example:

DecimalFormat df = new DecimalFormat("#.#");
df.format(rating);

Upvotes: -3

Related Questions