Python : 保留0的圆形浮点数
Python : Round float number keeping 0
我只需要舍入 Python
中浮点数的最后 2 个正数
EX:
- 0.000000302329303 -> 0.00000031
- 0.09838 -> 0.10
- 0.0003299 -> 0.00033
这是否可以通过像圆形这样的简单方式实现?
一种方法是计算以 10 为底的 log 指数,并取其负值:
import math
z = 1
x = 0.09838
rounded_x = round(x, math.ceil(-math.log10(x)) + z)
现在可以更改z来设置位数
请注意,通常使用 round 可能会将浮点数转换为科学表示形式(尾数和指数),因此在非常小的数字中它可能不太准确。
我认为你的示例是错误的,但请根据需要调整代码:
# 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)
这样就知道了
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
感谢大家,答案对我来说是必不可少的,让我能够想到一些东西。
我只需要舍入 Python
中浮点数的最后 2 个正数EX:
- 0.000000302329303 -> 0.00000031
- 0.09838 -> 0.10
- 0.0003299 -> 0.00033
这是否可以通过像圆形这样的简单方式实现?
一种方法是计算以 10 为底的 log 指数,并取其负值:
import math
z = 1
x = 0.09838
rounded_x = round(x, math.ceil(-math.log10(x)) + z)
现在可以更改z来设置位数
请注意,通常使用 round 可能会将浮点数转换为科学表示形式(尾数和指数),因此在非常小的数字中它可能不太准确。
我认为你的示例是错误的,但请根据需要调整代码:
# 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)
这样就知道了
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
感谢大家,答案对我来说是必不可少的,让我能够想到一些东西。