Truncating floats in Python

2019-01-01 12:55发布

I want to remove digits from a float to have a fixed number of digits after the dot, like:

1.923328437452 -> 1.923

I need to output as a string to another function, not print.

Also I want to ignore the lost digits, not round them.

26条回答
浮光初槿花落
2楼-- · 2019-01-01 13:54
# value  value to be truncated
# n  number of values after decimal

value = 0.999782
n = 3
float(int(value*1en))*1e-n
查看更多
泛滥B
3楼-- · 2019-01-01 13:56
def precision(value, precision):
    """
    param: value: takes a float
    param: precision: int, number of decimal places
    returns a float
    """
    x = 10.0**precision
    num = int(value * x)/ x
    return num
precision(1.923328437452, 3)

1.923

查看更多
登录 后发表回答