Python Removes Extra Zeros After Decimal Points
Recently, I've been using Python to write scripts for importing data. Baidu Bing searched a lot, none of them have a perfect solution.
Still have to spit out Baidu here for these are really crap.
Then FQ googled it and the first entry came up and found a way.
Here I've moved over to organize it and the problems you may encounter when using it. I hope it's useful for readers reading this
First introduce the header file
from decimal import Decimal
give an example
Number 100.2000
The first time I used Decimal('100.2000').normalize() this way, I got 100.2, which is the desired result.
But there is a problem with normalize(), if it is 100.00000 the same Decimal('100.0000').normalize() gets the result 1E+2
So what to do in this case is to change the method Use " to_integral ", like this: Decimal('100.000').to_integral() to get the result is 100, which is the desired result.
So how can the two be better compatible, you can first do a judgment after removing the excess 0 is equal:
>>> Decimal('100.2000') == Decimal('100.2000').to_integral() False >>> Decimal('100.0000') == Decimal('100.0000').to_integral() True
Based on this judgment, you can write your own function
def remove_exponent(num): return num.to_integral() if num == num.to_integral() else ()
The last call to this function is the same as in the examples above.
>>> remove_exponent(Decimal('100.2000')) Decimal('100.2') >>> remove_exponent(Decimal('100.0000')) Decimal('100') >>> remove_exponent(Decimal('0.2000')) Decimal('0.2')
The output here is Decimal because the method called is of this type. It can be used directly as a float, if you want to change it to a string type, just use str() to wrap the result above, this will not be explained.
This solves the problem of removing the extra zeros after the decimal point as stated in the title
Python removes zeros from the front of numbers
Sometimes the number of the file is generated in front of the automatic complement 0, and when we need to read these file names corresponding to the number, the front of the 0 will give the judgment statement to cause trouble, then how to remove the front of the 0 it?
Because Python defaults to ignoring leading zeros when converting to a string, de-zeroing can be accomplished by means of format conversion:
>>> str(000001) '1' >>> int(str(000001)) 1
The above is a personal experience, I hope it can give you a reference, and I hope you can support me more.