Ehsan R
Ehsan R

Reputation: 63

how to convert a float number to 4 decimal places without any rounding?

I'm going to take an integer number, then print root of that with sqrt function in float number to 4 decimal places without any rounding; but I have a problem. For example, when I take 3 as input, the output is 1.7320. It is correct; but when I take 4 as input, I expect 2.0000 as output; but what I see is 1.9999. What am I doing wrong?

import math
num = math.sqrt(float(input())) - 0.00005
print('%.4f' % num)

Upvotes: 2

Views: 5152

Answers (2)

vtnate
vtnate

Reputation: 163

Check out Round float to x decimals?

One of the solutions from that page would be to replace your print statement with: print(format(num, '.4'))

Using modern f-strings: print(f'{num:.4f}')

Upvotes: 4

benvc
benvc

Reputation: 15120

Based on your expected output for the square root of 3, it seems that you really just want to truncate or extend the square root output to 4 decimal places (rather than round up or down). If that is the case, you could just format to 5 decimal places and slice off the last character in the string (examples below replace your input with hardcoded strings for illustration).

import math

n = '{:.5f}'.format(math.sqrt(float('3')))[:-1]
print(n)
# 1.7320

n = '{:.5f}'.format(math.sqrt(float('4')))[:-1]
print(n)
# 2.0000

Upvotes: 1

Related Questions