Solved

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

Posted on 1999-01-21
1
1,064 Views
Last Modified: 2008-03-03
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
Comment
Question by:dbromberg
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
1 Comment
 
LVL 6

Accepted Solution

by:
PBall earned 50 total points
ID: 1280019
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

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Article by: DanRollins
This article describes a JavaScript program that creates a maze made of hexagonal cells.  In Part 2 (http://www.experts-exchange.com/Programming/Languages/Scripting/JavaScript/A_7850-Hex-Maze-Part-2.html), we'll extend the program by adding a depth-…
The task A number given should be formatted for easy reading by separating digits into triads. Format must be made inline via JavaScript, i.e., frameworks / functions are not welcome. So let’s take a number like this “12345678.91¿ and format i…
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…

691 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question