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:46
round(1.923328437452, 3)

See Python's documentation on the standard types. You'll need to scroll down a bit to get to the round function. Essentially the second number says how many decimal places to round it to.

查看更多
初与友歌
3楼-- · 2019-01-01 13:46

Something simple enough to fit in a list-comprehension, with no libraries or other external dependencies. For Python >=3.6, it's very simple to write with f-strings.

The idea is to let the string-conversion do the rounding to one more place than you need and then chop off the last digit.

>>> nout = 3  # desired number of digits in output
>>> [f'{x:.{nout+1}f}'[:-1] for x in [2/3, 4/5, 8/9, 9/8, 5/4, 3/2]]
['0.666', '0.800', '0.888', '1.125', '1.250', '1.500']

Of course, there is rounding happening here (namely for the fourth digit), but rounding at some point is unvoidable. In case the transition between truncation and rounding is relevant, here's a slightly better example:

>>> nacc = 6  # desired accuracy (maximum 15!)
>>> nout = 3  # desired number of digits in output
>>> [f'{x:.{nacc}f}'[:-(nacc-nout)] for x in [2.9999, 2.99999, 2.999999, 2.9999999]]
>>> ['2.999', '2.999', '2.999', '3.000']

Bonus: removing zeros on the right

>>> nout = 3  # desired number of digits in output
>>> [f'{x:.{nout+1}f}'[:-1].rstrip('0') for x in [2/3, 4/5, 8/9, 9/8, 5/4, 3/2]]
['0.666', '0.8', '0.888', '1.125', '1.25', '1.5']
查看更多
只靠听说
4楼-- · 2019-01-01 13:47

Simple python script -

n = 1.923328437452
n = float(int(n * 1000))
n /=1000
查看更多
唯独是你
5楼-- · 2019-01-01 13:49

I did something like this:

from math import trunc


def truncate(number, decimals=0):
    if decimals < 0:
        raise ValueError('truncate received an invalid value of decimals ({})'.format(decimals))
    elif decimals == 0:
        return trunc(number)
    else:
        factor = float(10**decimals)
        return trunc(number*factor)/factor
查看更多
人气声优
6楼-- · 2019-01-01 13:50

At my Python 2.7 prompt:

>>> int(1.923328437452 * 1000)/1000.0 1.923

查看更多
永恒的永恒
7楼-- · 2019-01-01 13:51

If you mean when printing, then the following should work:

print '%.3f' % number
查看更多
登录 后发表回答