Rob Alsod
Rob Alsod

Reputation: 2945

Python 3.3.2 - Rounding to a Number Whilst Keeping Decimals

I know the question sounds it a bit weird, I can't think of a way to explain it.

Basically, I need to round numbers without cutting off extra zeros and such. For example, my current format(round(whatever, 3)) will round something like 1.00000024 to 1.0, when I want it to round to 1.000. I know the practicality of this is stupid, but I need to do this so as to not confuse people when the numbers they get aren't the same length.

Help, please?

Upvotes: 0

Views: 752

Answers (1)

user2357112
user2357112

Reputation: 281923

The number of digits displayed after the decimal point isn't a property of the float representing the number - it's a property of how you display it. The format built-in or the string format method can use a format spec to control how numbers are displayed:

print('{:.3f}'.format(1.0))  # prints 1.000

See the links for how to use format specs - there are a lot of options, and they can get kind of confusing.

Upvotes: 5

Related Questions