B
B
BenderF2021-09-11 09:13:02
Python
BenderF, 2021-09-11 09:13:02

Output formatting?

Hello.
There is a simple Python program to calculate the factorial.

import math
while True:
    x = int(input("Введите число для вычисления факториала:  "))
    fc = math.factorial(x)
    print(" Факториал числа", x,  "равен", fc,  "цифр в числе - ", len(str(fc)))

Question! Is it possible to truncate (format) the value of the factorial of a variable (fc) so that it displays the first 5 digits of the number and puts a colon without converting to a string?
For example, the factorial of 100 has 158 digits, but the program should output the first 5 digits -> 93326..

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Sergey Karbivnichy, 2021-09-11
@BenderF

import math

def first_n_digits(num, n):
    return num // 10 ** (int(math.log(num, 10)) - n + 1)

while True:
    x = int(input("Введите число для вычисления факториала:  "))
    fc = math.factorial(x)
    print(" Факториал числа", x,  "равен", first_n_digits(fc,5),  ".. цифр в числе - ", len(str(fc)))

How can I get the first two digits of a number?

M
Michael, 2021-09-11
@lob4Noff

import math

while True:
    x = int(input("Введите число для вычисления факториала: "))
    fc = math.factorial(x)
    if len(str(fc)) > 5:
        print(f"Факториал числа {x} равен {str(fc)[:6]}..., цифр в числе - {len(str(fc))}")
    else:
        print(f"Факториал числа {x} равен {fc}, цифр в числе - {len(str(fc))}")

In this case, the type of the variable remains the same as it was.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question