[英]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;我将取一个整数,然后使用浮点数中的
sqrt
函数将它的根打印到小数点后 4 位,不进行任何四舍五入; but I have a problem.但我有一个问题。 For example, when I take 3 as input, the output is 1.7320.
例如,当我将 3 作为输入时,输出为 1.7320。 It is correct;
它是正确的; but when I take 4 as input, I expect 2.0000 as output;
但是当我将 4 作为输入时,我希望输出 2.0000; but what I see is 1.9999.
但我看到的是 1.9999。 What am I doing wrong?
我究竟做错了什么?
import math
num = math.sqrt(float(input())) - 0.00005
print('%.4f' % num)
Check out Round float to x decimals?查看圆形浮点数为 x 位小数?
One of the solutions from that page would be to replace your print statement with: print(format(num, '.4'))
该页面的解决方案之一是将您的打印语句替换为:
print(format(num, '.4'))
Using modern f-strings: print(f'{num:.4f}')
使用现代 f 字符串:
print(f'{num:.4f}')
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).根据您对 3 的平方根的预期输出,您似乎真的只想将平方根输出截断或扩展到 4 个小数位(而不是向上或向下舍入)。 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).
如果是这种情况,您只需格式化为 5 个小数位并切掉字符串中的最后一个字符(下面的示例将您的输入替换为硬编码字符串以进行说明)。
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.