首页 > 解决方案 > 如何在python中用尾随零舍入数字

问题描述

在excel中,有这个公式:=ROUNDDOWN(D28-D33-D34,-2)我得到了结果==> 166400。但是没有Rounddown公式的结果是==> 166468.50。我的问题是如何在 python 中得到相同的结果。当我进行回合(n,-2)时,我得到==> 166500。任何帮助将不胜感激!谢谢你。

标签: pythonroundingtrailing

解决方案


这是ROUNDDOWN(x,n)Python中函数的实现

def rounddown(x,n):
  return int(x// 10**n * 10**n)
  
print(rounddown(166468.50,1))   #166460
print(rounddown(166468.50,2))   #166400
print(rounddown(166468.50,3))   #166000

[更新]

该函数的新版本可以rounddown处理. (模拟 Excel 中的 ROUNDDOWN(x,n))n

def rounddown(x,n):
  sign=1 if n>0 else 0              # getting the sign of n.
  n=abs(n)                          # getting the absolute value of n.
  p= 10**n                          # calculating p the nth power of 10.
  result= (x // p) * p + sign * p   # calculating result.
  return int( result ) 

# sample result

print(rounddown(166468.50,1))   #166470
print(rounddown(166468.50,2))   #166500
print(rounddown(166468.50,3))   #167000
print(rounddown(166468.50,0))   #166468
print(rounddown(166468.50,-1))  #166460
print(rounddown(166468.50,-2))  #166400
print(rounddown(166468.50,-3))  #166000

推荐阅读