Reputation: 90
I need to round only the last 2 positives of a float number in Python
EX:
Is this possible in a simple way like round?
Upvotes: 1
Views: 398
Reputation: 90
got it this way
from math import ceil, floor
def float_round(num, direction = floor):
zeros = 0
number = num
while number < 0.1:
number *= 10
zeros += 1
places = zeros + 2
return direction(num * (10**places)) / float(10**places)
a = 43.0093
print(float_round(a, ceil)) ## 43.01
a = 0.018552876
print(float_round(a, ceil)) ## 0.019
a = 0.03352
print(float_round(a, ceil)) ## 0.034
a = 0.0998844
print(float_round(a, ceil)) ## 0.1
a = 0.1093
print(float_round(a, ceil)) ## 0.11
a = 33.0093
print(float_round(a, ceil)) ## 33.01
Thanks to everyone, the answer was essential for me to be able to think of something.
Upvotes: 1
Reputation: 812
One way to do it is to calculate the exponent with log in base 10, and take its negative value:
import math
z = 1
x = 0.09838
rounded_x = round(x, math.ceil(-math.log10(x)) + z)
Now you can change z to set the number of digits
Notice that in general using round might convert the float into scientific representation (mantissa and exponent), so in very small numbers it might be less accurate.
Upvotes: 1
Reputation: 652
I think your examples are wrong, but just adjust the code as you need:
# this code doesn't work if some are defined as 0.123 and others as .123
a = 0.000000302329303
nb_characters = len(str(a))
rounding_expr = "%%.%sf" % (nb_characters - 4)
rounded_a = float(rounding_expr % a)
Upvotes: 2