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.

JavaScript

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

JavaScript

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

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement