Python Forum
str.format rounding to the left of the decimal
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
str.format rounding to the left of the decimal
#1
Hi, I was wondering how I could make string.format round to the left of the decimal.


>>> x = 4. 542412343
>>> '{0} rounded to {1} decimals is {2: .1f}'.format(x, 4, x) 
>>> 4.5
>>> x = 52137809
>>> '{0} rounded to {1} decimals is {2: ???}'.format(x, 4, x) 
>>> 50000000
Moreover, is there somewhere I could have accessed this information, like the help function?

Thanks
Reply
#2
I do not believe that is possible. You would have to do some calculation on the number before string formatting. You can see the full format method syntax here.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply
#3
Probably you should round before displaying:

>>> x = 52137809
>>> '{0} rounded to tens of millions is {1}'.format(x, round(x, -7))  # format method
'52137809 rounded to tens of millions is 50000000'
>>> f'{x} rounded to tens of millions is {round(x, -7)}'              # f-string
'52137809 rounded to tens of millions is 50000000'
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  need help rounding joseph202020 7 1,257 Feb-21-2023, 08:13 PM
Last Post: joseph202020
  from numpy array to csv - rounding SchroedingersLion 6 2,063 Nov-14-2022, 09:09 PM
Last Post: deanhystad
  PyQT5 - align left frohr 7 3,835 May-07-2022, 09:56 PM
Last Post: deanhystad
  How did one column get left-justified? Mark17 6 1,877 Feb-26-2022, 11:55 PM
Last Post: deanhystad
  Random data generation sum to 1 by rounding juniorcoder 9 3,347 Oct-20-2021, 03:36 PM
Last Post: deanhystad
  Rounding issue kmll 1 1,379 Oct-08-2021, 10:35 AM
Last Post: Yoriz
  Not rounding to desired decimal places? pprod 2 2,504 Mar-05-2021, 11:11 AM
Last Post: pprod
  Decimal Rounding error project_science 4 2,696 Jan-06-2021, 03:14 PM
Last Post: project_science
  Can I format decimal places by column with a dictionary? Mark17 2 2,512 Dec-28-2020, 10:13 PM
Last Post: Mark17
  rounding and floats Than999 2 3,046 Oct-26-2020, 09:36 PM
Last Post: deanhystad

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020