简体   繁体   English

如何将浮点数转换为小数点后 4 位而不进行任何四舍五入?

[英]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.

相关问题 转换为浮点数而不舍入小数位数 - Convert to Float without Rounding Decimal Places 如何在不四舍五入的情况下将浮点数保留到小数点后两位 - How to get float to two decimal places without rounding off 如何将所有浮点数转换为两位小数,而不管浮点数有多少小数位,而无需重复转换代码? - How to convert all floats to two decimal places regardless of number of decimal places float has without repeating convert code? 如何在不四舍五入的情况下限制显示的一定数量的小数位? - How can limit a certain number of decimal places being shown without rounding? 如何将浮点数严格转换为整数,而不进行四舍五入? - How to convert float to integer strictly, without rounding? 如何格式化具有最大小数位数且没有额外零填充的浮点数? - How to format a float with a maximum number of decimal places and without extra zero padding? 如何将小数转换为 integer 而无需四舍五入 python 中的小数? - how to convert decimal to integer without rounding the decimal in python? 如何返回具有定义的小数位数的浮点数? - How to return a float point number with a defined number of decimal places? Pandas Dataframe 如何在不舍入的情况下截取浮点小数点? - Pandas Dataframe How to cut off float decimal points without rounding? 如何获得不带小数位的数字? - How to get number without decimal places?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM