A faster way to shift decimal in Python to remove zeros?

I have many numbers that are always limited to 0 and 1. The numbers matter, such as

.9, .08, .00024, .00000507

My goal is to convert these numbers to the next

.9, .8, .24, .507

That is, I want to remove any zeros after the decimal point.

I have the following code for this. Is there a way to do this faster in terms of performance?

import math
x=.009
n = int(-math.log10(x))
x *= math.pow(10, n)
+4
source share
2 answers

A faster way to do this (faster with larger numbers):

def method2(x):
    while x < 0.1:
        x *= 10
    return x

Even faster:

def method3(x):
    while x < 0.01:
        x *= 100
    while x < 0.1:
        x *= 10
    return x

A funny way to do this (slower than a question):

def remove_zeros(a):
    return float("0." + str(long(str(1+a)[2:])))
+2
source

This is not your expected result, but you can use it.

Decimals, , .

>>> from decimal import Decimal
>>> numbers = ['.9', '.08', '.00024', '.00000507']
>>> decimals = [Decimal(n) for n in numbers]
>>> [format(d, '.2E')[:4] for d in decimals]
['9.00', '8.00', '2.40', '5.07']

, , Decimals , . , :

[Decimal('0.90000000000000002220446049250313080847263336181640625'), Decimal('0.08000000000000000166533453693773481063544750213623046875'), Decimal('0.00024000000000000000608020578329870886591379530727863311767578125'), Decimal('0.0000050699999999999997388091914352070688210005755536258220672607421875')]

, .

0

Source: https://habr.com/ru/post/1533968/


All Articles