[Tutor] How to ignore some decimal values?
Mando Escamilla
mando@mando.org
17 Jan 2002 09:41:37 -0500
On Thu, 2002-01-17 at 10:47, dman wrote:
> On Wed, Jan 16, 2002 at 10:26:30PM -0800, Titu Kim wrote:
> | Hi there,
> | Do someone has any idea on keeping the floor value
> | of a fixed decimal point n? For instance:
> | a=12.3451
> | b=0.5699
> | c=0.0
> |
> | How can i make a,b, and c become float values as
> | a=12.34
> | b=0.56
> | c=0.00
> | if my n=2. If n=3
> | a=12.345
> | b=0.569
> | c=0.000
> |
> | Thanks for any suggestion?
>
> Ignoring the fact that binary floating point can't represent all
> decimal numbers :
>
> def truncate( f , n ) :
> shift = 10**n
> return int( f*shift ) / shift
>
> 'f' is the float you want to truncate,
> 'n' is an integer for the number of decimals you want to keep
>
> What it does is shift the decimal over so that all the digits you want
> are on the left side. Then convert to an int (drop all fractional
> part), then shift the decimal point back where it belongs.
You could also use fpformat, which seems to do the same thing :-).
>>> import fpformat
>>> a = 5.44444
>>> i = 1
>>> print fpformat.fix(a, i);
5.4
>>>
--
Mando