Skip to content
Advertisement

Round a floating point number to n digits ignoring leading zeros and preserving them

Floating Point = 11.0000123456789

I want to round the above floating point number to 11.00001235. So I want the base portion of the float rounded to 4 digits while ignoring and preserving the leading zeros and adding back in the significand at the end.

I have the following, it is short and sweet but feels a little bit like a work around.

import decimal

decimal.getcontext().prec = 4
significand, base = str(11.0000123456789).split('.')
fp = significand + str(decimal.Decimal('.' + base) + 0)[1:]  # I need to add 0 here for it to work
print(fp)

I can’t really find an answer to my specific question. I want to know what the most pythonic way of achieving this is or if what I have is decent enough. It feels a little shoddy to me.

Edit: the number of leading zeros is unknown and I chose four for the example. So I don’t think string formatting will work.

Advertisement

Answer

Edit: for an unknown number of 0’s I don’t see a better alternative than

import re
some_float = 11.00001203456789
how_many_to_keep = 4
regex = r"0[1-9]"
float_part = str(some_float).split(".")[1]
float_limiter = re.search(regex,float_part).start() if float_part.startswith("0") else -1
print(f'{some_float:2.{float_limiter+1+how_many_to_keep}f}')

Which is evaluating the number of 0 in real time using the expression float_limiter+1+how_many_to_keep, and use as a the format parameter. this has gotten a bit ugly but now returns the correct answer on all cases. The output is

11.00001235

3 People found this is helpful
Advertisement