in windows calculator the digits get seperated in thousands as you type in the number , how can it be done in python ? thanks

Recommended Answers

All 10 Replies

Do you already have some code for the calculator ? Are you using a GUI toolkit ?

long time ago I wrote a simple program that adds the amounts of checks and does some analysis on them for my business , it simply asks for the amount of the check and the dates . in Iran due to inflation most of the checks have too many zeros on them and it helps to see them seperated by ',' as we type them in , that was the reason I asked .

I am guessing that you used the built-in float type for this, but given that you are dealing with currency, I would recommend using the decimal module for representing the monetary value instead, to get the best control over the significant decimal places, and applying locale.currency() to format the value as a string. While the links I posted are for the Python 3.4 docs, thhis should apply to Python 2.7 as well.

Use string formatting

>>> value = 1000000000000
>>> n = "{:,}".format(value)
>>> print(n)
1,000,000,000,000
>>> #Back to float
>>> float(n.translate(None, ','))
1000000000000.0

thank you guys for your suggestions , but what I am looking for is this : suppose my program asks for the amount on the check , as I am typing , I like to see the numbers being seperated in thousands , in other words looking at snippsat code when I am asked for the value in line one , and I enter the number without ',' I want it to appear like line 4 eg:

>>> amount=int(input('please enter the amount of the check   '))
please enter the amount of the check   1,000,000,000

by the way @Schol-R-LEA my program reads in the numbers as integers because they all are but just to be complete I will re-write it to your suggestion

You need a GUI to do that, for example a tkinter Entry widget plus supporting code to handle each key stroke and mouse event sent to this widget.

thanks Gribouillis , that is what I thought too , but looking at snippsat code I got an idea , I can input the numbers using ',' (do I have to declare them as strings ? ) and then inside my code change them to float or int

Yes, you can enter the commas explicitely and parse the input later. For example you can remove every comma before converting to float or int

userdata = input('please enter the amount of the check   ')
userdata = userdata.replace(',', '')
amount = int(userdata)

You can improve this by adding a loop and input validation, for example a valid input matches the regex

r'^\s*\d{1,3}{\,\d{3}}*\s*$'

thanks Gribouillis , I have enough info to redo my code now . I have to brush up on regex , I have forgotten most of it . thanks again

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.