• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1085
  • Last Modified:

How To Use Math.round to round to only two decimal points?

How can you use math.round or a like object to round a number to two decimal places. Could I make this a function? How?
0
dbromberg
Asked:
dbromberg
1 Solution
 
PBallCommented:
As far as I know round will only round it to the closest integer, so... it's impossible to do this with just round.

However, consider this...

1. if you were to multiple the number by 100
   i.e.  3.1435030 * 100 = 314.35030

2. then round it up
   Math.round(314.35030), you will get 314

3. now, divide it back by 100
   i.e. 314 / 100 = 3.14

4. there you go, your answer is 3.14 (rounded to the nearest 2 decimal places.

so, the function you are looking for is:

function myRound( number , places )
{
  //heh, I forgot how to do the exponential, so don't laugh :)
  var factor = 10;
  for (var i = 0;i < places;i++) factor *= factor

  return (Math.round(number * factor))/factor
}

to round it to 3 decimal places, call it as:

myNumber = myRound(number_to_round,3)

0

Featured Post

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now