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:36

use numpy.round

import numpy as np
precision = 3
floats = [1.123123123, 2.321321321321]
new_float = np.round(floats, precision)
查看更多
后来的你喜欢了谁
3楼-- · 2019-01-01 13:37

The result of round is a float, so watch out (example is from Python 2.6):

>>> round(1.923328437452, 3)
1.923
>>> round(1.23456, 3)
1.2350000000000001

You will be better off when using a formatted string:

>>> "%.3f" % 1.923328437452
'1.923'
>>> "%.3f" % 1.23456
'1.235'
查看更多
闭嘴吧你
4楼-- · 2019-01-01 13:37

A general and simple function to use:

def truncate_float(number, length):
    """Truncate float numbers, up to the number specified
    in length that must be an integer"""

    number = number * pow(10, length)
    number = int(number)
    number = float(number)
    number /= pow(10, length)
    return number
查看更多
闭嘴吧你
5楼-- · 2019-01-01 13:37

There is an easy workaround in python 3. Where to cut I defined with an help variable decPlace to make it easy to adapt.

f = 1.12345
decPlace= 4
f_cut = int(f * 10**decPlace) /10**decPlace

Output:

f = 1.1234

Hope it helps.

查看更多
浅入江南
6楼-- · 2019-01-01 13:37

Am also a python newbie and after making use of some bits and pieces here, I offer my two cents

print str(int(time.time()))+str(datetime.now().microsecond)[:3]

str(int(time.time())) will take the time epoch as int and convert it to string and join with... str(datetime.now().microsecond)[:3] which returns the microseconds only, convert to string and truncate to first 3 chars

查看更多
心情的温度
7楼-- · 2019-01-01 13:40

The truely pythonic way of doing it is

from decimal import *

with localcontext() as ctx:
    ctx.rounding = ROUND_DOWN
    print Decimal('1.923328437452').quantize(Decimal('0.001'))
查看更多
登录 后发表回答