# [Tutor] Is there anyway to set how many numbers are used after the decimal in floating numbers?

Bob Gailer bgailer at alum.rpi.edu
Thu Aug 18 19:11:05 CEST 2005

```At 10:31 AM 8/18/2005, Nathan Pinno wrote:
>Is there anyway to set how many numbers are used after the decimal in
>floating numbers? It would be nice if the answer could be rounded to 2
>decimal spots, instead of the ten millionths spot.

The simple answer is NO. Floating point numbers have a "fixed" number of
digits and an exponent to place the decimal point. You can control how many
digits are "displayed" using % formatting.
>>> 5./3
1.6666666666666667
>>> '%6.3f' % (5./3) # notice this rounds and formats
' 1.667'

There are various other ways to accomplish your goals depending on what
they are. What are you using floating point numbers for? It is easy to get
into trouble with floating point arithmetic since (1) most decimal numbers
do not have an exact floating point representation, and (2) the limited
precision can caus cumulative errors. Example:
>>> i = 0.0
>>> for j in range(10):i += j*.1
>>> i
4.5000000000000009

If you have Python 2.4 + the decimal module may give you what you need.

Bob Gailer
303 442 2625 home
720 938 2625 cell

```