1

In Python, round can be used to round to n decimal digits. Now, round(0.229, 1) gives 0.2 and round(0.251, 1) gives 0.3. Is there a way in Python, to round them both in one direction, say, to 0.2? In other words, is there something analogous to floor or ceil for rounding to an integer, in the context of rounding to a certain number of decimal places?

Update: Accepting the solution based on decimal because it throws light on such a feature available in Python. The solutions based on dividing (and later multiplying) by a multiple of 10 are good ones and straightforward to use.

Hari
  • 1,561
  • 4
  • 17
  • 26

3 Answers3

1

You could use floor as follows:

def round_down(x):
    return math.floor(10*x) / 10

print(round_down(0.229))
print(round_down(0.251))

This prints:

0.2
0.2

The logic here is to first multiply up by 10, which then lets floor round down all decimal components other than the first one. Then, we divide again by 10 to generate the rounded-down number.

Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
1

You can use the decimal library:

from decimal import * 
print(Decimal(0.229).quantize(Decimal('.1'), rounding=ROUND_DOWN))
print(Decimal(0.251).quantize(Decimal('.1'), rounding=ROUND_DOWN))

Output:

0.2
0.2

You can also convert from Decimal to float:

f = float(Decimal(0.229).quantize(Decimal('.1'), rounding=ROUND_DOWN)))
Code Pope
  • 5,075
  • 8
  • 26
  • 68
  • Note that [wildcard imports should generally be avoided](https://stackoverflow.com/a/3615206/11021886) and are often considered bad practice – jwalton May 27 '20 at 14:30
  • @Ralph Although your point is generally correct, but even the python documentation uses it this way. I think this is due to size and names of the functions in the module. – Code Pope May 27 '20 at 14:43
  • Fair enough. I concede that there are exceptions to this rule, and this certainly appears to be such a case! – jwalton May 27 '20 at 14:59
1

There are already a couple of good answers to your question, however both solutions rely on external libraries. It is also possible to achieve what you desire with no imports:

def round_down(x):
    return int(10 * x) / 10

x = 0.251
round_down(x)
# 0.2
x = 0.229
round_down(x)
# 0.2

If you wanted something more similar to Python's round (where you can specify the number n of digits to round to), you could use:

def round_down(x, n=1):
    return int(10**n * x)  / 10**n

x = 0.229
round_down(x)
# 0.2
round_down(x, 2)
# 0.22

Depending how you'd like the rounding to behave for negative numbers, you may instead wish to define round_down(x) as:

def round_down(x):
    return 10 * x // 1 / 10
jwalton
  • 5,286
  • 1
  • 18
  • 36