在Python中截断为三位小数

Sup*_*ing 46 python

我如何获得1324343032.324?

如下所示,以下内容不起作用:

>>1324343032.324325235 * 1000 / 1000
1324343032.3243253
>>int(1324343032.324325235 * 1000) / 1000.0
1324343032.3239999
>>round(int(1324343032.324325235 * 1000) / 1000.0,3)
1324343032.3239999
>>str(1324343032.3239999)
'1324343032.32'
Run Code Online (Sandbox Code Playgroud)

Abh*_*Das 58

'%.3f'%(1324343032.324325235)

float()如果要将其保存为浮动,请在其周围使用其他附加项.

  • 如果你想舍入(向上)到给定的小数位数,这个答案是正确的.但是,问题是什么以及我想知道的是如何*将*截断为特定数量的小数位.对我来说,`'%.3f'%(1324343032.3243)`和''%.3f'%(1324343032.3245)`会给出不同的结果.(我使用的是Python 2.7.8). (7认同)
  • '%.2f' % 8866.316 是圆的但不是截断的 (4认同)
  • 这基本上是正确的答案,只需使用`val ='%.3f'%(1324343032.324325235)`而不是`print`. (3认同)
  • 这*不是*截断。 (3认同)
  • 你在四舍五入;看看我的回答 (2认同)

Erw*_*yer 30

您可以使用以下函数将数字截断为设定的小数:

import math
def truncate(number, digits) -> float:
    stepper = 10.0 ** digits
    return math.trunc(stepper * number) / stepper
Run Code Online (Sandbox Code Playgroud)

用法:

>> truncate(1324343032.324325235, 3)
>> 1324343032.324
Run Code Online (Sandbox Code Playgroud)

  • 这应该是公认的答案.代码简单,优雅,最有意义.使用标准截断函数,但首先移动小数位,一旦执行截断,将小数位移回. (6认同)

sol*_*eMe 11

我找到了另一个解决方案(它必须比"字符串巫术"解决方案更有效):

>>> import decimal
# By default rounding setting in python is decimal.ROUND_HALF_EVEN
>>> decimal.getcontext().rounding = decimal.ROUND_DOWN
>>> c = decimal.Decimal(34.1499123)
# By default it should return 34.15 due to '99' after '34.14'
>>> round(c,2)
Decimal('34.14')
>>> float(round(c,2))
34.14
>>> print(round(c,2))
34.14
Run Code Online (Sandbox Code Playgroud)

关于小数模块

关于舍入设置


AlG*_*AlG 7

这个怎么样:

In [1]: '%.3f' % round(1324343032.324325235 * 1000 / 1000,3)
Out[1]: '1324343032.324'
Run Code Online (Sandbox Code Playgroud)

Python中round()的可能重复似乎没有正确舍入

[编辑]

鉴于我认为你想做的其他评论:

In : Decimal('%.3f' % (1324343032.324325235 * 1000 / 1000))
Out: Decimal('1324343032.324')
Run Code Online (Sandbox Code Playgroud)

浮点精度不符合您的要求:

In : 3.324
Out: 3.3239999999999998
Run Code Online (Sandbox Code Playgroud)

(所有示例都使用Python 2.6.5)


pri*_*ens 6

使用十进制模块.但是如果你必须使用浮点数仍然以某种方式将它们强制转换为给定数量的小数点转换为字符串后面提供了一种(相当笨拙,我害怕)这样做的方法.

>>> q = 1324343032.324325235 * 1000 / 1000
>>> a = "%.3f" % q
>>> a
'1324343032.324'
>>> b = float(a)
>>> b
1324343032.324
Run Code Online (Sandbox Code Playgroud)

所以:

float("%3.f" % q)
Run Code Online (Sandbox Code Playgroud)


小智 6

我相信使用该format功能是一个坏主意。请参阅以下内容。它对值进行四舍五入。我使用 Python 3.6。

>>> '%.3f'%(1.9999999)
'2.000'
Run Code Online (Sandbox Code Playgroud)

改用正则表达式:

>>> re.match(r'\d+.\d{3}', str(1.999999)).group(0)
'1.999'
Run Code Online (Sandbox Code Playgroud)


gor*_*ndp 6

功能

def truncate(number: float, digits: int) -> float:
    pow10 = 10 ** digits
    return number * pow10 // 1 / pow10
Run Code Online (Sandbox Code Playgroud)

测试代码

f1 = 1.2666666
f2 = truncate(f1, 3)
print(f1, f2)
Run Code Online (Sandbox Code Playgroud)

输出

1.2666666 1.266
Run Code Online (Sandbox Code Playgroud)

解释

它将f1数字digits向左移动几次,然后去掉所有小数,最后将数字digits向右移回一次。

序列中的示例:

1.2666666 # number
1266.6666 # number * pow10
1266.0    # number * pow10 // 1
1.266     # number * pow10 // 1 / pow10
Run Code Online (Sandbox Code Playgroud)


mat*_*dev 5

'%.3f' %(1324343032.324325235)

在这种特殊情况下,这没关系.

只需稍微更改一下数字:

1324343032.324 7 25235

然后:

'%.3f'%(1324343032.324725235)
Run Code Online (Sandbox Code Playgroud)

给你1324343032.325

试试这个:

def trun_n_d(n,d):
    s=repr(n).split('.')
    if (len(s)==1):
        return int(s[0])
    return float(s[0]+'.'+s[1][:d])
Run Code Online (Sandbox Code Playgroud)

trun_n_d的另一个选项:

def trun_n_d(n,d):
    dp = repr(n).find('.') #dot position
    if dp == -1:  
        return int(n) 
    return float(repr(n)[:dp+d+1])
Run Code Online (Sandbox Code Playgroud)

trun_n_d为您提供Python 2.7和Python 3.6中所需的输出

trun_n_d(1324343032.324325235,3)返回1324343032.324

同样,trun_n_d(1324343032.324 7 25235,3)返回1324343032.324


注意在Python 3.6(以及可能在Python 3.x中)这样的东西,工作得很好:

def trun_n_d(n,d):
    return (  n if not n.find('.')+1 else n[:n.find('.')+d+1]  )
Run Code Online (Sandbox Code Playgroud)

但是,通过这种方式,四舍五入的幽灵总是潜伏着.


Zul*_*usK 5

I suggest next solution:

def my_floor(num, precision):
   return f'{num:.{precision+1}f}'[:-1]

my_floor(1.026456,2) # 1.02

Run Code Online (Sandbox Code Playgroud)

  • 需要多取一位数字然后将其删除,因为使用字符串_本身格式化数字会四舍五入数字_!例如: `f'{0.55:.2f}'[:-1]` 返回 `'0.5'`,但 `f'{0.55:.1f}'` 返回 `'0.6'`。这也是为什么该解决方案在像“1.9999999”这样的病理情况下会失败的原因。它将始终返回“2.0x”,其中“0x”表示与所需精度一样多的零。 (2认同)