bdo334
bdo334

Reputation: 408

Using toFixed(2) and math round to get correct rounding

I would like to find a function that will return this kind of formatted values :

1.5555 => 1.55
1.5556 => 1.56
1.5554 => 1.55
1.5651 => 1.56

toFixed() and math round return this value :

1.5651.fixedTo(2) => 1.57

This will be usefull for money rounding.

Upvotes: 5

Views: 22278

Answers (3)

Jaroslav Moravec
Jaroslav Moravec

Reputation: 428

And standard function

fixedTo = function (number, n) {
  var k = Math.pow(10, n);
  return (Math.round(number * k) / k);
}

and then call

fixedTo(1.5555, 2)  // 1.56
fixedTo(1.5555, 2)  // 1.556
fixedTo(0.615, 2)   // 0.62

Upvotes: 3

Johnny Oshika
Johnny Oshika

Reputation: 57482

You can use the native Number.toFixed() method.

parseFloat(10.159.toFixed(2))

The above returns 10.16. Number.toFixed() returns a string, so I use parseFloat to convert it to a number.

Upvotes: 1

Mark Bessey
Mark Bessey

Reputation: 19782

How about this?

function wacky_round(number, places) {
    var multiplier = Math.pow(10, places+2); // get two extra digits
    var fixed = Math.floor(number*multiplier); // convert to integer
    fixed += 44; // round down on anything less than x.xxx56
    fixed = Math.floor(fixed/100); // chop off last 2 digits
    return fixed/Math.pow(10, places);
}

1.5554 => 1.55

1.5555 => 1.55

1.5556 => 1.56

1.5651 => 1.56

So, that works, but I think you'll find that it's not a generally-accepted way to round. http://en.wikipedia.org/wiki/Rounding#Tie-breaking

Upvotes: 6

Related Questions