Aligning Print to Decimal Place

17 views
Skip to first unread message

Dr. Clark Vangilder

unread,
Sep 22, 2022, 12:30:49 PM9/22/22
to Glowscript Users
I assumed that print(f'{x:>.2f}  {slope:>.2f}  {df(x):>.2f}') within a while loop would align the three output variable columns "x", "slope", and "df(x)" in this Trinket (https://trinket.io/glowscript/0a0592d60d), but no, kinda.

So long as the numbers are exactly the same length, it all lines up, but as soon as they switch sign or increase/decrease the number of integer place holders, it's off. I've tried a few solutions from Stack Exchange etc. but they don't seem to work.

What am I missing?

NOTE: the print output for this Trinket isn't very useful towards it main purpose of comparing a limit process to an analytic answer, but I was just curious about the outputs and it became frustrating to fail at formatting it. A solution would be most helpful in a bunch of other settings.

Bruce Sherwood

unread,
Sep 22, 2022, 2:50:29 PM9/22/22
to Glowscript Users
I didn't realize that there are is a vast number of options available with Python f-strings. For example, in the following there is a space between the ":" and the ".2f" the numbers all align properly:

a = 2.4
b = 10
c = 9.6

print(f'{a: .2f} {b: .2f} {c: .2f}')
print(f'{a: .2f} {-b: .2f} {-c: .2f}')

I don't even know what your ">" element is supposed to do. Maybe in the vast world of f-string options there is something that does what you want. It seemed possible that the RapydScript-NG Python-to-JavaScript doesn't implement all of the f-string machinery, but I ran your program with installed Python and the output was the same, so it's not a VPython issue.

Bruce

Dr. Clark Vangilder

unread,
Sep 22, 2022, 3:00:58 PM9/22/22
to Glowscript Users
The > is supposed to right-align. < is left, ^ is center, and there are a few more I think.

I've tried your suggestions as well, print(f'{x: .2f}  {slope: .2f}  {df(x): .2f}'), but here is what you get in my Trinket.

-2.80  -10.80  -11.20
-2.60  -10.00  -10.40
-2.40  -9.20  -9.60
-2.20  -8.40  -8.80
-2.00  -7.60  -8.00

Bruce Sherwood

unread,
Sep 22, 2022, 5:55:00 PM9/22/22
to Glowscript Users
As I indicated, I know little about f-strings. But since I see the same behavior with installed Python, it's apparently not a VPython issue. Rather, it would seem to be a question about what is the f-string syntax that does what you want.

Bruce
Reply all
Reply to author
Forward
0 new messages