5

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.

6
  • 1
    You have the fourth decimal affect the second decimal? When ever would you use this? Commented May 18, 2010 at 20:50
  • 6
    Why would you want to round in such a strange way? How would this be useful for money rounding? Commented May 18, 2010 at 20:55
  • 1
    Your examples don't really seem to be getting your point across. What's the rule you're trying to enforce, exactly? Round down on a final "5" digit, unless the next digit is > 5? Commented May 19, 2010 at 0:22
  • Indeed, this is a strange way of rounding. Doesn't really make any sense to me. Commented May 19, 2010 at 0:51
  • 1
    Isn't that how Richar Pryor made all that money in that Superman movie? Commented May 19, 2010 at 1:33

3 Answers 3

6

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

Sign up to request clarification or add additional context in comments.

2 Comments

Sorry, copy and paste error while formatting for the site. Oh, and you're clear on why you shouldn't use this rounding method, right?
it was not for my consumption ;) however the one asking wanted to round amounts from .181 to .18 and .185 to .19 which I am never so sure of. toFixed(2) feels wrong in these cases.
3

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

1 Comment

This solution doesn't work for 1.005. I recommend using this function instead
1

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.