简体   繁体   中英

Python3: How to round up to a specific number?

I would like to round up to the next 1, 2 or 5 decimal value like in the following code example.

        if result > 0.1:
            if result > 0.2:
                if result > 0.5:
                    if result > 1.0:
                        if result > 2.0:
                            if result > 5.0:
                                if result > 10.0:
                                    if result > 20.0:
                                        if result > 50.0:
                                            rounded_result = 100.0
                                        else:
                                            rounded_result = 50.0
                                    else:
                                        rounded_result = 20.0
                                else:
                                    rounded_result = 10.0
                            else:
                                rounded_result = 5.0
                        else:
                            rounded_result = 2.0
                    else:
                        rounded_result = 1.0
                else:
                    rounded_result = 0.5
            else:
                rounded_result = 0.2
        else:
            rounded_result = 0.1

Eg for values between 0.1 and 0.2 rounded_result should be 0.2, for values between 0.2 and 0.5 rounded_result should be 0.5 and so on.

Is there a smarter way of doing this?

A function like this, maybe?

It expects thresholds to be in ascending order.

def round_threshold(value, thresholds):
    for threshold in thresholds:
        if value < threshold:
            return threshold
    return value


thresholds = [0, 0.1, 0.2, 0.5, 1.0, 2.0, 5.0, 10.0, 20.0, 50.0, 100.0]

for test in (0.05, 0.15, 11.3, 74, 116):
    print(test, round_threshold(test, thresholds))

The output is

0.05 0.1
0.15 0.2
11.3 20.0
74 100.0
116 116
thresholds = [0, 0.1, 0.2, 0.5, 1.0, 2.0, 5.0, 10.0, 20.0, 50.0, 100.0]

for i,thresh in enumerate(thresholds):
    if value<thresh:
        print(thresholds[i])
        break
    if value>thresholds[-1]:
        print(thresholds[-1])
        break

This is the vectorized alternative:

def custom_round(value, boundaries):
    index = np.argmin(np.abs(boundaries - value)) + 1
    if index < boundaries.shape[0]:
        return boundaries[index]
    else:
        return value

import numpy as np    

boundaries = np.array([0, 0.1, 0.2, 0.5, 
                   1.0, 2.0, 5.0, 10.0, 
                   20.0, 50.0, 100.0])

## test is from @AKX (see other answer)
for test in (0.05, 0.15, 11.3, 74, 116):
   print(test, custom_round(test, boundaries))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM