Home > Blockchain >  dividing a number into one hundredth
dividing a number into one hundredth

Time:11-23

Python program Help who knows .

My task:

Write a program that separates natural numbers into hundredths with commas (counting from the right). The program accepts a natural number as input.

Conditions:

If the number is less than three characters, the program displays the text NO.

Sample program:

Initial data: 14875 Imprint: 14,875

Intial data: 148 Imprint: NO

CodePudding user response:

Not sure what do you mean by comma at hundredth place. So, I'm answering for both possibilities.

num = 1487526645
num_str = str(num)
result = ''
counter = 0
for i in range(len(num_str) - 1, -1, -1):

    if len(num_str) <= 3:
        result = 'NO'
        break
    counter  = 1
    result = num_str[i]   result
    if counter % 3 == 0:
        result = ','   result

print(result)

will give you the output 1,487,526,645.

and

num = 1487526645
num_str = str(num)
result = ''
counter = 0
for i in range(len(num_str) - 1, -1, -1):

    if len(num_str) <= 3:
        result = 'NO'
        break
    counter  = 1
    result = num_str[i]   result
    if (counter % 3 == 0 and counter <= 3) or ((counter - 3) % 2 == 0 and counter > 3):
        result = ','   result

print(result)

will give you the output 1,48,75,26,645.

P.S.- As others will mention, it's a good practice to show your work before asking others for a solution. It shows your effort which everyone appreciates and encourages to help you.

CodePudding user response:

f"{numb:,}" will do this for you in python3. No need to write your own function(s)/class(es).

  • Related