I need to get qty
number by a specified precision
like below:
qty = 0.1284
precision = 0.01
output = 0.12
It seems easy, buy I could not get it done because I have a precision
above variable.
Floating math is not precise - see Is floating point math broken?.
You can use round() to round - you seem to want to truncate though - you can do this mathematically:
qty = 0.1284
precision = 0.01
truncated = ((qty * (1/precision)) // 1 ) * precision
print(truncated)
Output:
0.12
This multiplies your number with the correct factor, integer divides by 1 to get rid of remaining partial digits and multiplies by precision again to get back to your float value.
Note that rounding the number in-memory may still lead to display imprecisions, as most floating point numbers wil remain approximations of the decimal expectation.
It works, but when I have qty like 181.1231231221, it prints 181.10000000000002.