My code has shown well up to the second decimal place so far.
res4 = Decimal(‘%.2f’ % (res4 * 100 / 100))
but i got error…
35.3169 –> 35.32
Why is it being raised?
I want to throw everything away from the third decimal place.
help bro!!!
>Solution :
If you don’t want to round numbers, you can truncate floats with string operations like this:
def truncate_number(num, limit):
int_part, fract_part = str(float(num)).split('.')
return float(f'{int_part}.{fract_part[:limit]}')
In [9]: truncate_number(35.3169, 2)
Out[9]: 35.31
In [9]: truncate_number(1.1199, 2)
Out[9]: 1.11
In [11]: truncate_number(1.1199, 3)
Out[11]: 1.119
In [11]: truncate_number(-1.1199, 3)
Out[11]: -1.119
Keep in mind that this function wont convert 1 to 1.000:
In [13]: truncate_number(1, 3)
Out[13]: 1.0