devxlogo

Round to a Whole Number

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) = 16Math.ceil(15.3) = 15

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

Example:

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

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

Example:

Math.floor(15.65) = 15Math.floor(15.3) = 15

See also  Who are the Modern GPU Cloud Providers?
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist