Search code examples
pythonnumbersnumber-formatting

How to format numbers without rounding in Python?


I was searching online but could find if this is posible. I have a number, let say 1234.5963657 and I know that with f-string I can do this f"{number:,.2f}" to obtain 1,234.60.

The thing is that the number has been rounded, and I don't want that, I would like to obtain: 1,234.59. My question is if there's a way to do this as simple as the f-string.

If not, I would have to truncate it or do something like this:

number = 1234.5963657
int_part, dec_part = str(number).split('.')
new_number = f"{int_part}.{dec_part[:2]}" # 1234.59

Hope my question is clear. Thanks


Solution

  • Add one more digit of precision then use a slice to exclude the unwanted digit.

    f"{number:,.3f}"[:-1]