-3

I'm looking for an output of

4.33 = 4.5

4.5517263843648 = 5

Using the Math.round function in javascript. I've tried a few methods but neither seem to work.

Cerbrus
  • 70,800
  • 18
  • 132
  • 147
Erik
  • 47
  • 1
  • 9
  • Math.round(), Math.floor() and Math.ceil() always round to the nearest, lower and upper integer. In order to round to the nearest integer or half integer you should make a function that does the math. Stack Overflow is not a site to ask for someone else to do it for you. Post what you have tried – R. Schifini Aug 13 '15 at 12:23
  • _"you should make a function that does the math"_... How does that help at all? – Cerbrus Aug 13 '15 at 12:23
  • just ganna leave this here: `[1,2,1.2,1.8,1.5,1.3].map(function(v){return v + ": " + Math.round(v*2)/2}).join(", ")` – GottZ Aug 13 '15 at 12:30
  • 1
    @GottZ: Did you get that from the answer on the duplicate link? – Cerbrus Aug 13 '15 at 12:31
  • 1
    @Cerbrus nope i got it from trying it here: http://chat.stackoverflow.com/transcript/message/25068302#25068302 – GottZ Aug 13 '15 at 12:36

1 Answers1

1

Try to use,

function test(val) {
    var x = Math.floor(val);
    return (val - x) > 0.5 ? Math.ceil(val) : (x + 0.5);
}

DEMO

Rajaprabhu Aravindasamy
  • 66,513
  • 17
  • 101
  • 130