Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: Math processing
Expertise: Beginner
Nov 2, 1999

Round to a Whole Number

Question:

I have a program that calculates the number of people the government could send to college with the money they spend on certain defense programs. The script works, but when I divide the cost of the education into the cost of the program, I get a number with lots of decimal places. As you know, there is no such thing as .5647389 of a person, so is there a way to lop that decimal off of my answer?

Answer:

There are three ways to convert a number with decimals into a whole number. Which method you use depends on how you'd like to do the conversion.

Math.round(number)
This is the most common way to turn a number with decimals into a whole number. The return value is the nearest whole number. Technically, if the decimal portion of the number is 0.5 or greater the method returns the smallest integer that is greater than the number, otherwise the largest integer that's less than or equal to number is returned. Note that this may not be what you expect for negative numbers.

Example:

Math.round(15.65) = 16
Math.ceil(15.3) = 15

Math.ceil(number)
This always rounds up to the larger whole number.

Example:

Math.ceil(15.65) = 16
Math.ceil(15.3) = 16

Math.floor(number)
This always rounds down, effectively removing the decimals.

Example:

Math.floor(15.65) = 15
Math.floor(15.3) = 15
DevX Pro
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date