How to round to a higher 10 place in python

I have a bunch of floats and I want to round them to the next highest multiple of 10.

For example:

10.2 should be 20 10.0 should be 10 16.7 should be 20 94.9 should be 100 

I need it to go from a range of 0-100. I tried math.ceil () but only rounds to the nearest integer.

Thanks in advance.

+7
python math
source share
4 answers
 from math import ceil def ceil_to_tens(x): return int(ceil(x / 10.0)) * 10 

Edit : ok, now that I have the undeserved "Good Answer" badge for this answer, I believe that the community should have the right solution using the decimal module, which does not suffer from these problems :) Thanks to Jeff for this. Thus, a solution using decimal works as follows:

 from decimal import Decimal, ROUND_UP def ceil_to_tens_decimal(x): return (Decimal(x) / 10).quantize(1, rounding=ROUND_UP) * 10 

Of course, the above code requires that x be an integer, string, or decimal object - floats will not work, as this can damage the whole purpose of using the decimal module.

It is Decimal.quantize that Decimal.quantize does not work properly with digits greater than 1, this would save the division-multiplication trick.

+12
source share
 >>> x = 16.7 >>> int( 10 * math.ceil(x/10.0)) 
+3
source share

The answers here are fraught with danger. For example, 11*1.1 - 2.1 = 10.0 , right? But wait:

 >>> x = 11*1.1 - 2.1 >>> int(ceil(x / 10.0)) * 10 20 >>> x 10.000000000000002 >>> 

You can try this

 int(ceil(round(x, 12) / 10.0)) * 10 

But choosing the number of decimal places to round to is very difficult, since it is difficult to predict how floating point noise accumulates. If it is really important that all this time is correct, you need to use fixed-point arithmetic or Decimal.

+1
source share

If you are looking for another solution that does not include float separation, here is a module that uses a module:

 def ceil_to_tens_mod(x): tmp = int(ceil(x)) mod10 = tmp % 10 return tmp - mod10 + (10 if mod10 else 0) 

There is probably a way to simplify it, but there you go.

0
source share

All Articles