TomNg
TomNg

Reputation: 1997

Round up floats to first decimal point

I want a number to be rounded up to first decimal position

>>> round(1.2345, 2)
1.3
>>> round(1.261, 2)
1.3

I know one solution so far

>>> math.ceil(1.2345 * 10) / 10
1.3

Is there another way?

Upvotes: 3

Views: 1063

Answers (1)

Ozgur Vatansever
Ozgur Vatansever

Reputation: 52093

You can use decimal.ROUND_UP and .quantize()to round a decimal to a fixed number of places:

>>> from decimal import Decimal, ROUND_UP
>>> Decimal(1.2345).quantize(Decimal(".1"), rounding=ROUND_UP)
Decimal('1.3')

You can play around with the first parameter (precision) to specify the number of digits you want:

>>> Decimal(1.2375).quantize(Decimal(".001"), rounding=ROUND_UP)
Decimal('1.238')

Upvotes: 3

Related Questions