After looking for a way to solve this problem, without loading any Python 3 module or extra mathematical operations, I solved the problem using only str.format() e .float(). I think this way is faster than using other mathematical operations, like in the most commom solution. I needed a fast solution because I work with a very very large dataset and so for its working very well here.
def truncate_number(f_number, n_decimals): strFormNum = "{0:." + str(n_decimals+5) + "f}" trunc_num = float(strFormNum.format(f_number)[:-5]) return(trunc_num) # Testing the 'trunc_num()' function test_num = 1150/252 [(idx, truncate_number(test_num, idx)) for idx in range(0, 20)]
It returns the following output:
[(0, 4.0), (1, 4.5), (2, 4.56), (3, 4.563), (4, 4.5634), (5, 4.56349), (6, 4.563492), (7, 4.563492), (8, 4.56349206), (9, 4.563492063), (10, 4.5634920634), (11, 4.56349206349), (12, 4.563492063492), (13, 4.563492063492), (14, 4.56349206349206), (15, 4.563492063492063), (16, 4.563492063492063), (17, 4.563492063492063), (18, 4.563492063492063), (19, 4.563492063492063)]
decimalmodule or some other arbitrary-precision math library, such asgmpy.int(1324343032.324325235 * 1000) / 1000.0seems to work well