How can I limit the decimal places of a 'float' in python without rounding the number?
For example:
a = 1.45698946
>>
Limit_a = 1.45698
And not:
1.45699
How can I limit the decimal places of a 'float' in python without rounding the number?
For example:
a = 1.45698946
>>
Limit_a = 1.45698
And not:
1.45699
This is long winded, but will give you the constituent parts to do something more elegant.
decimalPlaces = 5
val = 1.45698946
mod = 10 ** decimalPlaces
truncated = float(int(val * dps)) / dps
For values with less than 5 decimal places, you get the original value.
To avoid float precision errors I recommend using decimal
module:
from decimal import Decimal
a = 1.45698946
limit_a = str(int(a)) + str(Decimal(str(a)) % 1)[1:7]
print(float(limit_a))
Output is:
1.45698