User123456789
User123456789

Reputation: 115

Format float to decimals (ones, tens, hundreds ...)

In the round() function it is possible to go from a float to i.e. a number rounded to the ten-spot:

round(123.2,-1) yields 120

or

round(123,2,0) yields 123

Is there a way to do the same thing using format?

Like: "{:.-1f}".format(123.2) = "120"

or in other notation?

format(123.2,.-1f)="120"

Upvotes: 0

Views: 1008

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1121624

No, you can't. Formatting specifies the width of the output (where number of digits after the decimal is really a width adjustment), where rounding is only used to achieve the right width.

Just round first, then format the rounded result.

In Python 3.6 and newer, you can put the rounding expression in an f-string, of course:

f'Result: {round(123.2, -1)}'

Upvotes: 1

Related Questions