gerald BARY
gerald BARY

Reputation: 1

how to round down numbers with a trailing zero in python

In excel, there is this formula: =ROUNDDOWN(D28-D33-D34, -2) and I got the results ==> 166400. But the result without the Rounddown formulas is ==> 166468.50. My question is how to get the same in python. When I do round (n, -2) I get ==> 166500. Any help would be much appreciated! Thank you.

Upvotes: 0

Views: 152

Answers (1)

AziMez
AziMez

Reputation: 2072

This is an implementation of the ROUNDDOWN(x,n) function in 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

[Update]

A new version of the function rounddown, that can handle both positive and negative values of n. (simulate the ROUNDDOWN(x,n) found in Excel)

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

Upvotes: 2

Related Questions