Reputation: 613
Say I have an arbitrary float x = 123.123456
and want to remove the last n decimal digits from the float i.e. n = 1
then x = 123.12345
, n = 2
then x = 123.1234
and so on. How can this be achieved in python?
Upvotes: 1
Views: 2699
Reputation: 5264
This will do the trick you are asking, but be mindful of the issues with floating point numbers.
# let's cut 2 digits
n = 2
# naively we can do this
f = 123.123456
short_f = float(str(f)[:-n])
# but watch out for floating point error
f = 1.2 - 1.0 # f should be 0.2 but is actually 0.19999999999999996
short_f = float(str(f)[:-n]) # so this gives 0.199999999999999
This sounds like an XY problem, maybe you are looking for round
or string formatting.
Upvotes: 2