Issue
I'd like to remove all leading zeros from decimals.
For example 0,0000000029 should be 29 instead or 0,000000710 should be 710 instead.
Whats is the easiest way to achieve this in python?
Sorry if this is an obvious question, but I did not find any concrete answer yet and I'm an absolute beginner.
Edit: I want to use this for a Binance crypto trading bot I'm programming. Every currency has a precision, so the maximum float length is always given. When the price of a currency is for example 0,00000027 I would like to have it returned as 27.
Solution
Here is a simple way to do it using string manipulation:
# Your number, defined to 10 decimal places
x = 0.0000001230
# Convert to string using f-strings with 10 decimal precision
out = f'{x:.10f}'
# Split at the decimal and take the second element from that list
out = out.split('.')[1]
# Strip the zeros from the left side of your split decimal
out = out.lstrip('0')
out
>>> '1230'
As a one-liner:
out = f'{x:.10f}'.split('.')[1].lstrip('0')
If you want the final result to be an integer or a float, simply convert it after using int(out)
or float(out)
.
Edit: if you want to change the precision (has to be fixed precision to account for trailing zeros), you just need to change the int appearing in the f-string: out = f'{x:.<precision>f}'
.
Answered By - Philip Ciunkiewicz Answer Checked By - David Marino (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.