If you’re printing only 4 decimals and you don’t want the number rounded that means you want the decimals truncated and regular formatting methods don’t provide facilities for that.
You can easily achieve that if you pre-process your number as:
def truncate_number(number, decimals):
factor = 10.0 ** decimals
return int(number * factor) / factor
num = float(input('Enter a number: '))
num_sqrt = num ** 0.5 # or math.sqrt(num) if that's what you prefer.
print("The square root of {:.4f} is {:.4f}".format(num, truncate_number(num_sqrt, 4)))
It essentially just multiplies the number with 10^number_of_decimals
, truncates the decimals by converting it to an int
and then divides it with the same multiplication factor – this, in effect, leaves only the decimals you’re interested in.
You don’t even nedd to use formatting directives after pre-processing your number as Python won’t print trailing zeros so a simple print("The square root of {} is {}".format(num, truncate_number(num_sqrt, 4)))
should suffice.
2
solved The second root of a number is up to four digits without decomposing it