MindaugasM
MindaugasM

Reputation: 11

Dynamic decimal point Python float

I'm looking for a way to neatly show rounded floats of varying decimal lengh.

Example of what I'm looking for:

In: 0.0000000071234%
Out: 0.0000000071%

In: 0.00061231999999%
Out: 0.0061%

In: 0.149999999%
Out: 0.15%

One way to do it would be:

def dynamic_round(num):
    zeros = 2
    original = num
    while num< 0.1:
        num*= 10
        zeros += 1
    return round(original, zeros)

I'm sure however there is a much cleaner way to do the same thing.

Upvotes: 0

Views: 942

Answers (2)

ghost_ds
ghost_ds

Reputation: 13

This post answers your question with a similar logic How can I format a decimal to always show 2 decimal places? but just to clarify

One way would be to use round() function also mentioned in the documentation built-in functions: round()

>>> round(number[,digits]) 

here digit refers to the precision after decimal point and is optional as well.

Alternatively, you can also use new format specifications

>>> from math import pi  # pi ~ 3.141592653589793
>>> '{0:.2f}'.format(pi)
'3.14'

here the number next to f tells the precision and f refers to float.

Another way to go here is to import numpy

>>>import numpy
>>>a=0.0000327123
>>>res=-int(numpy.log10(a))
>>>round(a,res+2)
>>>0.000033

numpy.log() also, takes an array as an argument, so if you have multiple values you can iterate through the array.

Upvotes: 0

Roy2012
Roy2012

Reputation: 12523

Here's a way to do it without a loop:

a = 0.003123
log10 = -int(math.log10(a))
res = round(a, log10+2)

==> 0.0031

Upvotes: 1

Related Questions