0

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

Alex Turner
  • 698
  • 6
  • 16
  • 1
    Does this answer your question? [Python setting Decimal Place range without rounding?](https://stackoverflow.com/questions/29246455/python-setting-decimal-place-range-without-rounding) – mkrieger1 Dec 09 '22 at 16:11
  • I read it before creating this post, but I find my way with strings "quicker" – Alex Turner Dec 09 '22 at 16:13
  • I believe the word you are looking for is "truncate" – Jab Dec 09 '22 at 16:16
  • Yes, I would like to truncate the number, but not like the math.trunc() function which only returns the integer part of the number, because I need also 2 decimals. – Alex Turner Dec 09 '22 at 16:21
  • 1
    Does this answer your question? [Truncate to three decimals in Python](https://stackoverflow.com/questions/8595973/truncate-to-three-decimals-in-python) – Gert Arnold Dec 09 '22 at 18:17
  • I just check it, I thought it could work, but the same round up happens, I will have to do like the solution I marked, like this: ('%.3f'%number)[:-1]. With that it would work. – Alex Turner Dec 12 '22 at 12:21

1 Answers1

1

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

f"{number:,.3f}"[:-1]
wwii
  • 23,232
  • 7
  • 37
  • 77