0

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.

MindaugasM
  • 11
  • 3
  • 2
    Does this answer your question? [How do I make a float only show a certain amount of decimals](https://stackoverflow.com/questions/62782367/how-do-i-make-a-float-only-show-a-certain-amount-of-decimals) – Jacques Jul 29 '20 at 17:55
  • The last example (.1499999) isn't rounding. Are you certain that's the correct output? – Roy2012 Jul 29 '20 at 17:57
  • Roy2012 you're right, typo on my part. Fixed. – MindaugasM Jul 29 '20 at 18:05
  • You might consider using Decimals instead of floats: `from decimal import Decimal` – Andrew Allaire Jul 29 '20 at 18:06
  • @MindaugasM, it will be good if you [accept](https://stackoverflow.com/help/someone-answers) answer which helped you to solve your problem. – Olvin Roght Jul 30 '20 at 07:49

2 Answers2

1

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
Roy2012
  • 11,755
  • 2
  • 22
  • 35
0

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.

ghost_ds
  • 13
  • 5