[BangPypers] Need Help : Setting Floating Precision Point as 2 in Python

Noufal Ibrahim noufal at gmail.com
Tue Aug 24 14:12:33 CEST 2010


Arulalan T <arulalant at gmail.com> writes:

[...]

>> Often, you *need* to only display the result of your calculations with n
>> decimal places. Is yours such a situation? If so, forget the number of
>> decimal points during the computation and when printing format it as
>> appropriate ("%.2f").
>>
>>
> I am not just printing the float value.

I'm quite sure that you're doing more than printing. I'm asking you
whether the 2 decimal places business applies at all levels of the
program or only at the display level.

>> >>> import decimal
>> >>> a = decimal.Decimal("79.73")
>> >>> b = decimal.Decimal("0.5")
>>
>
>
>> >>> str(a + b)
>>
>
>
>> '80.23'
>>
>
> This is wrong ans.


79.73 + 0.5 is 80.23.

Why is this a wrong answer?


>>>> str(a+b)
> '80'.
>
> i.e. '80' only, not '80.23'.
>
> And I dont want this in string. I need only in float value, that too exactly
> in precision 2.

That's just the string representation. You got it because you called
"str" on the value.

>>> import decimal
>>> a = decimal.Decimal("79.73")
>>> b = decimal.Decimal("0.5")
>>> a + b
Decimal('80.23')


[...]

> I am doing project for Indian Meteorological Department using CDAT python
> library.
>
> Now I am plotting weather symbol markers on India Map at corresponding
> latitude and longitude (in float) dynamically.
> Due to inaccuracy floating value of latitude & logitude,
> the position of markers are moved away from the exact position of the
> stations on the map.
>
> so I need float value in 2 precision without changing the value. Not in
> string.
>
> Any suggestions?

[...]

Well, you shouldn't be using floating point numbers to represent things
like currency, longitude/latitute etc. 

What is the problem with the decimal module?

You can fine tune the precision of your current execution thread using
the getcontext method

>>> import decimal
>>> decimal.getcontext().prec = 2            # Two decimal points
>>> decimal.Decimal(1) / decimal.Decimal(7)  
Decimal('0.14')
>>> decimal.getcontext().prec = 15           # 15 decimal points
>>> decimal.Decimal(1) / decimal.Decimal(7)
Decimal('0.142857142857143')
>>> 






-- 


More information about the BangPypers mailing list