• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar
The Electric Toolbox Blog

The Electric Toolbox Blog

Linux, Apache, Nginx, MySQL, Javascript and PHP articles

  • Applications
  • FCKEditor
  • Apache
  • Windows
  • Contact Us
Home / Rounding numbers with Javascript

Rounding numbers with Javascript

The Javascript Math object has various mathematical functions and constants including .round() for rounding, ceil() for rounding numbers up and floor() for rounding numbers down.

Math.round()

Math.round() will round the number to the nearest integer. There is no parameter for precision so the resulting number will always be an integer. If the decimal part is .5 or higher, the number is rounded up. Here are some examples:

document.write( Math.round(1.4) ); // writes 1
document.write( Math.round(1.5) ); // writes 2

document.write( Math.round(-1.5) ); // writes -1
document.write( Math.round(-1.6) ); // writes -2

Math.floor()

Math.floor() will always round the number down to the nearest integer. As with Math.round() there is no provision for precision so the resulting number is always an integer. Even if the decimal part is .9999 the number will be rounded down. Here are some examples, using the same numbers as above:

document.write( Math.floor(1.4) ); // writes 1
document.write( Math.floor(1.5) ); // writes 1

document.write( Math.floor(-1.5) ); // writes -2
document.write( Math.floor(-1.6) ); // writes -2

Math.ceil()

Math.ceil() will always round the number up (ceil = ceiling). Again there’s no precision, so the function only returns integers. And the examples again use the same numbers:

document.write(Math.ceil(1.4)); // writes 2
document.write(Math.ceil(1.5)); // writes 2

document.write(Math.ceil(-1.5)); // writes -1
document.write(Math.ceil(-1.6)); // writes -1

Check Out These Related posts:

  1. Get an element’s position relative to the document with jQuery
  2. CSS3 rounded corner input
  3. Rounding numbers with PHP
  4. Rounding numbers with MySQL

Filed Under: Javascript

Primary Sidebar

Categories

  • Apache
  • Applications
  • Article
  • Case Studies
  • Email Servers
  • FCKEditor
  • HTML And CSS
  • Javascript
  • Linux/Unix/BSD
  • Microsoft SQL Server
  • Miscellaneous Postings
  • MySql
  • Networking
  • Nginx Web Server
  • Offsite Articles
  • OSX
  • PHP
  • Quick Tips
  • RFC – Request for Comments
  • SilverStripe
  • VMWare
  • VPN
  • Windows
  • WordPress

Recent Posts

  • Vim Show Line Numbers
  • Add User To Group Linux
  • Chmod 777 Tutorial
  • How to Copy Directory Linux
  • Linux create user

Copyright © 2021. ElectricToolBox. All Rights Reserved.

  • Contact Us
  • Copyright Info
  • Privacy Policy
  • Sitemap