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

6
  • 1
    Does this answer your question? Python setting Decimal Place range without rounding? Commented Dec 9, 2022 at 16:11
  • I read it before creating this post, but I find my way with strings "quicker" Commented Dec 9, 2022 at 16:13
  • I believe the word you are looking for is "truncate" Commented Dec 9, 2022 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. Commented Dec 9, 2022 at 16:21
  • 1
    Does this answer your question? Truncate to three decimals in Python Commented Dec 9, 2022 at 18:17

1 Answer 1

1

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

f"{number:,.3f}"[:-1]
Sign up to request clarification or add additional context in comments.

1 Comment

Ohhh, nice, I think this could be the best way of doing it, let me try it

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.