Software, your way.
How To Get Good Custom Software
(Download)
(PDF)
burger menu icon
WillMaster

WillMaster > LibraryTutorials and Answers

FREE! Coding tips, tricks, and treasures.

Possibilities weekly ezine

Get the weekly email website developers read:

 

Your email address

name@example.com
YES! Send Possibilities every week!

JavaScript Rounding

This is a tutorial for using JavaScript to round numbers.

It is about how to do the rounding, rather than how to use the numbers after they are rounded. In the example code, the JavaScript alert() function is used for displaying results of rounding.

The reason for the tutorial is that coding a web page may sometimes require a number to be rounded.

An example is a div positioned and sized according to the viewing area when a page loads, and repositioned or resized when the dimensions of the viewing area change or when the user has been on the page for over a certain amount of time.

On-the-fly calculations may require rounding for use in other inline CSS values, too. Or financial calculations may need rounding.

This tutorial was written for whatever reason a rounded number may be required.

It has code for rounding a decimal number to (a) the next higher integer, (b) the next lower integer, or (c) the nearest integer.

It also has code for rounding decimal numbers to a required number of decimals.

The JavaScript

If all you need to do is round a decimal number to an integer, one line of code can do the job.

To round up to the next higher integer, use the Math.ceil() function.

To round down to the next lower integer, use the Math.floor() function.

And to round to the nearest integer, use the Math.round() function.

Here is an example of each.

<script type="text/javascript">

var number_to_round = 1234.5678;

// Round up to the next higher integer.
var result = Math.ceil(number_to_round);
alert(number_to_round + " rounded up: "+result);
// Expected result: 1235

// Round down to the next lower integer.
result = Math.floor(number_to_round);
alert(number_to_round + " rounded down: "+result);
// Expected result: 1234

// Round to the nearest integer.
result = Math.round(number_to_round);
alert(number_to_round + " rounded nearest: "+result);
// Expected result: 1235

</script>

But if you want the rounding to result in a decimal number, more code is needed.

More Versatile Rounding

Below is the source code for a function named RoundTheNumber() that can be an all-purpose rounding function, for integers or decimals. Put the source code somewhere on the web page (or pulled in from an external file).

No customization is required. Just paste it into your web page anywhere that JavaScript can run — near the bottom of the page immediately above the </body> tag is a good spot.

<script type="text/javascript">
function RoundTheNumber()
{
   var ta = new Array();
   for(var i=0; i<arguments.length; i++) { ta.push(arguments[i]); }
   if( ta.length < 1 ) { return false; }
   var number = parseFloat(ta.shift());
   var count = ta.length;
   if(count===0)
   {
      ta.push('r');
      ta.push(false);
   }
   else if(count===1)
   {
      var s = new String(ta[0]);
      ta[0] = s;
      if(ta[0].match(/^\d+$/) )
      {
         ta.push(ta[0]);
         ta[0] = 'r';
      }
      else { ta.push(false); }
   }
   if(ta[0].match(/^u/i) || ta[0].match(/^c/i)) { ta[0] = 'c'; }
   else if(ta[0].match(/^d/i) || ta[0].match(/^f/i)) { ta[0] = 'f'; }
   else { ta[0] = 'r'; }
   if( ta[1] )
   {
      var zeros = new String( ((1.0).toFixed(ta[1])).substr(2) );
      var md = parseInt("1"+zeros);
      switch(ta[0])
      {
         case 'c' : return (Math.ceil(number*md)/md).toFixed(ta[1]);
         case 'f' : return (Math.floor(number*md)/md).toFixed(ta[1]);
         case 'r' : return (Math.round(number*md)/md).toFixed(ta[1]);
      }
   }
   switch(ta[0])
   {
      case 'c' : return Math.ceil(number);
      case 'f' : return Math.floor(number);
      default  : return Math.round(number);
   }
}
</script>

When the above JavaScript source code is available on the web page, it can be used.

The RoundTheNumber() function can be called with up to three parameters:

  1. The number to round (required).

    This can be any valid integer or floating point (decimal) number.

  2. The direction to round (optional).

    This parameter, if used, can be any of these values (the values are not case-sensitive):

    • ceil (or c) to indicate a rounding up to the next higher integer or decimal.
    • floor (or f) to indicate a rounding down to the next lower integer or decimal.
    • round (or r) to indicate a rounding the nearest integer or decimal.

    The default for this parameter is round for rounding the nearest integer or decimal.

  3. The required number of decimals to round to (optional).

    If the rounding is to be to a certain number of decimals instead of to an integer, then specify the number of decimals to round to.

    The default for this parameter is false (0 decimals).

Here is code you can use to test the RoundTheNumber() function.

<script type="text/javascript">

var number_to_round = 1234.5678;

// Round to the nearest integer.
var result = RoundTheNumber(number_to_round);
alert(number_to_round + " rounded nearest integer: "+result);
// Expected result: 1235

// Round to the nearest 2 decimal places.
result = RoundTheNumber(number_to_round,"round",2);
alert(number_to_round + " rounded nearest 2 decimals: "+result);
// Expected result: 1234.57

// Round down to the next lowest 2 decimal places.
result = RoundTheNumber(number_to_round,"floor",2);
alert(number_to_round + " rounded lowest 2 decimals: "+result);
// Expected result: 1234.56

</script>

Using It

As indicated, the Math.ceil(), Math.floor(), and Math.round() functions can be used for quick rounding to an integer.

For rounding to decimal numbers, the RoundTheNumber() function can be used. When it is available to the web page, the function can be used to round numbers to both integers and specific number of decimals

(This article first appeared with an issue of the Possibilities newsletter.)

Will Bontrager

Was this article helpful to you?
(anonymous form)

Support This Website

Some of our support is from people like you who see the value of all that's offered for FREE at this website.

"Yes, let me contribute."

Amount (USD):

Tap to Choose
Contribution
Method

All information in WillMaster Library articles is presented AS-IS.

We only suggest and recommend what we believe is of value. As remuneration for the time and research involved to provide quality links, we generally use affiliate links when we can. Whenever we link to something not our own, you should assume they are affiliate links or that we benefit in some way.

How Can We Help You? balloons
How Can We Help You?
bullet Custom Programming
bullet Ready-Made Software
bullet Technical Support
bullet Possibilities Newsletter
bullet Website "How-To" Info
bullet Useful Information List

© 1998-2001 William and Mari Bontrager
© 2001-2011 Bontrager Connection, LLC
© 2011-2024 Will Bontrager Software LLC