Python rounding does not work because of scientific number

Question:

Very simple, I want to round my ‘base_price’ and ‘entry’ with the precision, here 0.00001. It doesn’t work because it converts it to a scientific number.
How do I do this; I have been stuck for 1 hour.

Some post says to use output="{:.9f}".format(num) but it adds some zero after the last 1.

It work with precision = str(0.0001) but start from 4 zeros after the dot, it change to scientific numbers and digit = precision[::-1].find('.') doesn’t work with scientific numbers.

precision = str(0.00001) #5 decimals after the dot
print(precision)
base_price=0.0314858333
entry=0.031525

digit = precision[::-1].find('.')
entry_price = float(round(float(entry), digit))
base_price = float(round(float(base_price), digit))
print(entry_price,base_price)

Expected result:

base_price=0.03148 #5 decimals after the dot
entry=0.03152 #5 decimals after the dot
Asked By: One boy

||

Answers:

If you want to round to a precision given by a variable, you can just do

precision = 0.00001
entry = 0.031525
entry_price = round(entry / precision) * precision
Answered By: LeopardShark

It sounds like you want to truncate the number, so:

precision = 0.00001
base_price = 0.0314858333

# use int to truncate the division to the nearest fraction. 
base_price = int(base_price / precision) * precision 
print(base_price) # prints 0.03148
Answered By: Waterski24

To use numbers in the format ‘0.00001’ to set precision instead of the number you want, I’d use int(abs(math.log10(precision))) then pass that number to format.

Like so

import math
precision = 0.00001
precision_count = int(abs(math.log10(precision)))

base = 0.0314858333
entry = 0.031525

print(f"{entry:.{precision_count}f}, {base:.{precision_count}f}")

(I’ve removed suffix _price from base_price because in one case you used entry and entry_price and in the other you used base_price twice, so I went with the first standard for both)

I’d recommend you test with multiple possible values of precision

But, you probably should be using Decimal instead

Based on the variable names having "price", you could run into rounding problems/error compounding. To avoid surprises, I recommend you use decimal (or something with similar capabilities). In your case, quantize seems to be what you’re looking for.

Answered By: user19513069
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.