How to round a number to significant figures in Python How to round a number to significant figures in Python python python

How to round a number to significant figures in Python


You can use negative numbers to round integers:

>>> round(1234, -3)1000.0

Thus if you need only most significant digit:

>>> from math import log10, floor>>> def round_to_1(x):...   return round(x, -int(floor(log10(abs(x)))))... >>> round_to_1(0.0232)0.02>>> round_to_1(1234243)1000000.0>>> round_to_1(13)10.0>>> round_to_1(4)4.0>>> round_to_1(19)20.0

You'll probably have to take care of turning float to integer if it's bigger than 1.


%g in string formatting will format a float rounded to some number of significant figures. It will sometimes use 'e' scientific notation, so convert the rounded string back to a float then through %s string formatting.

>>> '%s' % float('%.1g' % 1234)'1000'>>> '%s' % float('%.1g' % 0.12)'0.1'>>> '%s' % float('%.1g' % 0.012)'0.01'>>> '%s' % float('%.1g' % 0.062)'0.06'>>> '%s' % float('%.1g' % 6253)'6000.0'>>> '%s' % float('%.1g' % 1999)'2000.0'


If you want to have other than 1 significant decimal (otherwise the same as Evgeny):

>>> from math import log10, floor>>> def round_sig(x, sig=2):...   return round(x, sig-int(floor(log10(abs(x))))-1)... >>> round_sig(0.0232)0.023>>> round_sig(0.0232, 1)0.02>>> round_sig(1234243, 3)1230000.0