Wednesday, December 26, 2012

Round Floating Point Numbers In Python

Python is a versatile programming language used for Web and desktop development. Part of Python's appeal is the large variety of libraries and built-in functions bundled with the programming language. With these built-ins, programmers can perform simple mathematical tasks. By using the "round()" function, you can round decimal numbers, and with the "math" package, you can perform more advanced rounding tasks.








Instructions>>round(4.5)


5.0 // "5" in Python 3


>>>round(4.567)


4.5999 //approximately 4.6, decimal representation is never entirely accurate in programming


2. Use the "ceil()" function to round a decimal. The "ceil()" (ceiling) function rounds a number in a particular way. Instead of rounding to the nearest whole number, it rounds to the nearest whole number toward positive infinity. For example, 4.5 will round to 5, but -4.5 will round to -4. The following example illustrates the "ceil()" function:


>>>import math


>>>math.ceil(3.1)


4.0


>>>math.ceil(-3.9)


-3.0


3. Use the "floor()" function to round a decimal. The "floor()" function behaves in the opposite way that the "ceil()" function does. Rather than rounding towards positive infinity, the "floor()" function rounds toward negative infinity. The following example illustrates the "floor()" function:


>>>import math


>>>math.floor(3.9)


3.0


>>>math.floor(-3.1)


-4.0

Tags: floor function, ceil function, function round, function round decimal, round decimal, >>>import math