如何使用 Python 四舍五入到小数点后 2 位?[重复]
- 2024-12-18 08:39:00
- admin 原创
- 211
问题描述:
我在此代码(华氏度到摄氏度转换器)的输出中得到了很多小数。
我的代码目前如下所示:
def main():
printC(formeln(typeHere()))
def typeHere():
global Fahrenheit
try:
Fahrenheit = int(raw_input("Hi! Enter Fahrenheit value, and get it in Celsius!
"))
except ValueError:
print "
Your insertion was not a digit!"
print "We've put your Fahrenheit value to 50!"
Fahrenheit = 50
return Fahrenheit
def formeln(c):
Celsius = (Fahrenheit - 32.00) * 5.00/9.00
return Celsius
def printC(answer):
answer = str(answer)
print "
Your Celsius value is " + answer + " C.
"
main()
所以我的问题是,如何让程序将每个答案四舍五入到小数点后第二位?
解决方案 1:
您可以使用该round
函数,其第一个参数是数字,第二个参数是小数点后的精度。
对于你的情况,应该是:
answer = str(round(answer, 2))
解决方案 2:
使用str.format()
的语法显示两位小数(不改变 的底层值) :answer
`answer`
def printC(answer):
print("
Your Celsius value is {:0.2f}ºC.
".format(answer))
在哪里:
:
引入格式规范0
为数字类型启用符号感知零填充.2
将精度设置为2
f
将数字显示为定点数
解决方案 3:
大多数答案都建议round
或format
。round
有时会向上舍入,而就我而言,我需要将变量的值向下舍入,而不仅仅是显示出来。
round(2.357, 2) # -> 2.36
我在这里找到了答案:如何将浮点数四舍五入到小数点后一位?
import math
v = 2.357
print(math.ceil(v*100)/100) # -> 2.36
print(math.floor(v*100)/100) # -> 2.35
或者:
from math import floor, ceil
def roundDown(n, d=8):
d = int('1' + ('0' * d))
return floor(n * d) / d
def roundUp(n, d=8):
d = int('1' + ('0' * d))
return ceil(n * d) / d
解决方案 4:
如果只想打印出舍入结果,则可以使用自 Python 3.6 开始引入的f 字符串str.format()
。语法与的格式字符串语法相同,只是将 a 放在f
文字字符串前面,并将变量直接放在字符串中的花括号内。
.2f
表示四舍五入到小数点后两位:
number = 3.1415926
print(f"The number rounded to two decimal places is {number:.2f}")
输出:
The number rounded to two decimal places is 3.14
解决方案 5:
您可以使用圆形函数。
round(80.23456, 3)
答案是 80.234
在你的情况下,使用
answer = str(round(answer, 2))
解决方案 6:
您想将自己的答案四舍五入。
round(value,significantDigit)
是执行此操作的常用解决方案,但是当您要四舍五入的数字紧接着的下一位(左边)的数字具有 时,这有时5
并不像从数学角度预期的那样运行。
以下是这种不可预测行为的一些示例:
>>> round(1.0005,3)
1.0
>>> round(2.0005,3)
2.001
>>> round(3.0005,3)
3.001
>>> round(4.0005,3)
4.0
>>> round(1.005,2)
1.0
>>> round(5.005,2)
5.0
>>> round(6.005,2)
6.0
>>> round(7.005,2)
7.0
>>> round(3.005,2)
3.0
>>> round(8.005,2)
8.01
假设您的意图是进行科学统计的传统四舍五入,这是一个方便的包装器,可以使函数round
按预期工作,而不需要import
额外的内容,例如Decimal
。
>>> round(0.075,2)
0.07
>>> round(0.075+10**(-2*6),2)
0.08
啊哈!因此我们可以在此基础上创建一个函数...
def roundTraditional(val,digits):
return round(val+10**(-len(str(val))-1), digits)
基本上,这会向字符串添加一个非常小的值,以强制它在不可预测的情况下正确舍入,而函数通常不会round
像您期望的1e-X
那样舍入。要添加的一个方便的值是,您尝试在 plus 上X
使用的数字字符串的长度。round
`1`
使用的方法10**(-len(val)-1)
是经过深思熟虑的,因为它是您可以添加的最大的最小数字,以强制移位,同时还确保即使.
缺少小数,添加的值也不会改变舍入。我可以使用10**(-len(val))
条件if (val>1)
来减去1
更多...但更简单的是始终减去,1
因为这不会改变此解决方法可以正确处理的适用十进制数范围。如果您的值达到类型的限制,此方法将失败,但对于几乎整个有效十进制值范围,它都应该有效。
因此最终的代码将会是这样的:
def main():
printC(formeln(typeHere()))
def roundTraditional(val,digits):
return round(val+10**(-len(str(val))-1))
def typeHere():
global Fahrenheit
try:
Fahrenheit = int(raw_input("Hi! Enter Fahrenheit value, and get it in Celsius!
"))
except ValueError:
print "
Your insertion was not a digit!"
print "We've put your Fahrenheit value to 50!"
Fahrenheit = 50
return Fahrenheit
def formeln(c):
Celsius = (Fahrenheit - 32.00) * 5.00/9.00
return Celsius
def printC(answer):
answer = str(roundTraditional(answer,2))
print "
Your Celsius value is " + answer + " C.
"
main()
...应该会给你带来你所期望的结果。
您也可以使用十进制库来实现这一点,但我建议的包装器更简单,在某些情况下可能更受欢迎。
编辑:感谢Blckknght指出这里的5
边缘情况仅针对某些值发生。
解决方案 7:
如果您需要避免会计四舍五入数字时的浮点问题,可以使用 numpy round。
您需要安装 numpy:
pip install numpy
和代码:
import numpy as np
print(round(2.675, 2))
print(float(np.round(2.675, 2)))
印刷
2.67
2.68
如果您使用合法的四舍五入来管理资金,那么您应该使用它。
解决方案 8:
float(str(round(answer, 2)))
float(str(round(0.0556781255, 2)))
解决方案 9:
如果您不仅需要四舍五入结果,而且还需要对四舍五入结果进行数学运算,那么您可以使用decimal.Decimal
https://docs.python.org/2/library/decimal.html
from decimal import Decimal, ROUND_DOWN
Decimal('7.325').quantize(Decimal('.01'), rounding=ROUND_DOWN)
Decimal('7.32')
解决方案 10:
from decimal import Decimal, ROUND_HALF_UP
# Here are all your options for rounding:
# This one offers the most out of the box control
# ROUND_05UP ROUND_DOWN ROUND_HALF_DOWN ROUND_HALF_UP
# ROUND_CEILING ROUND_FLOOR ROUND_HALF_EVEN ROUND_UP
our_value = Decimal(16.0/7)
output = Decimal(our_value.quantize(Decimal('.01'),
rounding=ROUND_HALF_UP))
print output
解决方案 11:
只需使用 %.2f 格式即可四舍五入到小数点后 2 位。
def printC(answer):
print "
Your Celsius value is %.2f C.
" % answer
解决方案 12:
您可以使用四舍五入运算符,最多保留 2 位小数
num = round(343.5544, 2)
print(num) // output is 343.55
解决方案 13:
可以使用python的字符串格式化运算符“%”。“%.2f”表示小数点后2位。
def typeHere():
try:
Fahrenheit = int(raw_input("Hi! Enter Fahrenheit value, and get it in Celsius!
"))
except ValueError:
print "
Your insertion was not a digit!"
print "We've put your Fahrenheit value to 50!"
Fahrenheit = 50
return Fahrenheit
def formeln(Fahrenheit):
Celsius = (Fahrenheit - 32.0) * 5.0/9.0
return Celsius
def printC(answer):
print "
Your Celsius value is %.2f C.
" % answer
def main():
printC(formeln(typeHere()))
main()
http://docs.python.org/2/library/stdtypes.html#string-formatting
解决方案 14:
为了避免 round() 产生的惊人值,这是我的方法:
Round = lambda x, n: eval('"%.'+str(int(n))+'f" % '+repr(int(x)+round(float('.'+str(float(x)).split('.')[1]),n)))
print(Round(2, 2)) # 2.00
print(Round(2.675, 2)) # 2.68
解决方案 15:
截断为 2 位数字:
somefloat = 2.23134133
truncated = int( somefloat * 100 ) / 100 # 2.23
解决方案 16:
下面是我使用的一个例子:
def volume(self):
return round(pi * self.radius ** 2 * self.height, 2)
def surface_area(self):
return round((2 * pi * self.radius * self.height) + (2 * pi * self.radius ** 2), 2)
解决方案 17:
round(12.3956 - 0.005, 2) # minus 0.005, then round.
答案来自: https: //stackoverflow.com/a/29651462/8025086
解决方案 18:
这是我迄今为止发现的最简单的解决方案,不知道为什么人们不使用它。
# Make sure the number is a float
a = 2324.55555
# Round it according to your needs
# dPoints is the decimals after the point
dPoints = 2
# this will round the float to 2 digits
a = a.__round__(dPoints)
if len(str(a).split(".")[1]) < dPoints:
# But it will only keep one 0 if there is nothing,
# So we add the extra 0s we need
print(str(a)+("0"*(dPoints-1)))
else:
print(a)
解决方案 19:
因为您希望以十进制数表示答案,所以您不需要在 printC() 函数中将答案变量类型转换为 str。
然后使用printf 样式的字符串格式化
解决方案 20:
不知道为什么,但 '{:0.2f}'.format(0.5357706) 给出了 '0.54'。对我(python 3.6)来说唯一有效的解决方案如下:
def ceil_floor(x):
import math
return math.ceil(x) if x < 0 else math.floor(x)
def round_n_digits(x, n):
import math
return ceil_floor(x * math.pow(10, n)) / math.pow(10, n)
round_n_digits(-0.5357706, 2) -> -0.53
round_n_digits(0.5357706, 2) -> 0.53
扫码咨询,免费领取项目管理大礼包!