newbypyth
newbypyth

Reputation: 131

Round to the next tens in Python

Is there a way to round always up to the next tens? E.g., 0.000000000003 shall become 0.1. 0.1244593249234 shall become 0.2 and 0.9x shall become 1. Negative numbers are not a thing here.

Is there a built in or do I need to come up with something?

Upvotes: 2

Views: 651

Answers (3)

OmG
OmG

Reputation: 18838

by multiplying the input f to 10, you will map it from [0, 1] to [0, 10]. Now by getting ceil from this number, you will get an integer number in [0, 10] that by dividing it by 10, you will obtain the next ten in [0, 1] range as you desire:

import math

next_ten = math.ceil(f * 10.0) / 10.0

Upvotes: 1

Buddy Bob
Buddy Bob

Reputation: 5889

Idk, it's a simple solution. I tested it out for all the options you gave and seems to work properly.

x = 0.2
print("{:.1f}".format(x+.1))

Upvotes: 1

Matiiss
Matiiss

Reputation: 6156

here ya go. this is not built in and probably too excessive but it should work at least, work is done:

number = input()

number = number.split('.')
first = int(number[-1][0])

if first == 9:
    number = str(int(number[0]) + 1)
else:
    for digit in number[-1][1:]:
        if digit != '0':
            first += 1
            break

    number = number[0] + '.' + str(first)

print(number)

Upvotes: 0

Related Questions