[Tutor] Is there anyway to set how many numbers are used after the decimal in floating numbers?
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.
>>> '%6.3f' % (5./3) # notice this rounds and formats
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
If you have Python 2.4 + the decimal module may give you what you need.
303 442 2625 home
720 938 2625 cell
More information about the Tutor