我在这段代码的输出中得到了很多小数(华氏温度到摄氏温度转换器).
我的代码目前看起来像这样:
def main():
printC(formeln(typeHere()))
def typeHere():
global Fahrenheit
try:
Fahrenheit = int(raw_input("Hi! Enter Fahrenheit value, and get it in Celsius!\n"))
except ValueError:
print "\nYour 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 "\nYour Celsius value is " + answer + " C.\n"
main()
Run Code Online (Sandbox Code Playgroud)
所以我的问题是,如何使程序围绕小数点后两位的每个答案?
rol*_*isz 321
您可以使用round函数,该函数将第一个参数作为数字,第二个参数作为精度.
在你的情况下,它将是:
answer = str(round(answer, 2))
Run Code Online (Sandbox Code Playgroud)
Joh*_*web 63
使用str.format()的语法,以显示 answer具有两个小数位(不改变的基础值answer):
def printC(answer):
print("\nYour Celsius value is {:0.2f}ºC.\n".format(answer))
Run Code Online (Sandbox Code Playgroud)
哪里:
s4w*_*0ff 40
问题是标注:"怎么舍下降到2位小数"
大多数答案建议round或format.round有时会向上舍入,在我的情况下,我需要将变量的值始终向下舍入(不仅仅是这样显示).
round(2.357, 2) # -> 2.36
Run Code Online (Sandbox Code Playgroud)
我在这里找到了真正的答案:如何将浮点数舍入到某个小数位?
import math
v = 2.357
print(math.ceil(v*100)/100) # -> 2.36
print(math.floor(v*100)/100) # -> 2.35
Run Code Online (Sandbox Code Playgroud)
要么:
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
Run Code Online (Sandbox Code Playgroud)
jac*_*314 19
如果您只想打印四舍五入的结果,您可以使用自 Python 3.6 以来引入的f-strings。语法与str.format()的格式字符串语法相同,不同之处f在于您将 a放在文字字符串的前面,并将变量直接放在字符串中,在花括号内。
.2f 表示四舍五入到两位小数:
number = 3.1415926
print(f"The number rounded to two decimal places is {number:.2f}")
Run Code Online (Sandbox Code Playgroud)
输出:
The number rounded to two decimal places is 3.14
Run Code Online (Sandbox Code Playgroud)
Sam*_*zon 13
如果您需要避免在四舍五入的数字上出现浮点问题以进行会计处理,您可以使用 numpy round。
你需要安装 numpy :
pip install numpy
Run Code Online (Sandbox Code Playgroud)
和代码:
import numpy as np
print(round(2.675, 2))
print(float(np.round(2.675, 2)))
Run Code Online (Sandbox Code Playgroud)
印刷
2.67
2.68
Run Code Online (Sandbox Code Playgroud)
如果您使用合法四舍五入来管理资金,则应该使用它。
Rya*_*der 12
如果您不仅需要舍入结果,还需要对舍入结果进行数学运算,那么您可以使用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')
Run Code Online (Sandbox Code Playgroud)
Rom*_*man 11
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
Run Code Online (Sandbox Code Playgroud)
小智 9
float(str(round(answer, 2)))
float(str(round(0.0556781255, 2)))
Run Code Online (Sandbox Code Playgroud)
小智 8
您可以使用round函数。
round(80.23456, 3)
Run Code Online (Sandbox Code Playgroud)
会给你80.234的答案
在你的情况下,使用
answer = str(round(answer, 2))
Run Code Online (Sandbox Code Playgroud)
您可以将舍入运算符用于最多 2 位小数
num = round(343.5544, 2)
print(num) // output is 343.55
Run Code Online (Sandbox Code Playgroud)
可以使用python的字符串格式化运算符“%”。“%.2f”表示小数点后2位。
def typeHere():
try:
Fahrenheit = int(raw_input("Hi! Enter Fahrenheit value, and get it in Celsius!\n"))
except ValueError:
print "\nYour 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 "\nYour Celsius value is %.2f C.\n" % answer
def main():
printC(formeln(typeHere()))
main()
Run Code Online (Sandbox Code Playgroud)
http://docs.python.org/2/library/stdtypes.html#string-formatting
只需使用%.2f的格式,它可以向下舍入到2位小数.
def printC(answer):
print "\nYour Celsius value is %.2f C.\n" % answer
Run Code Online (Sandbox Code Playgroud)
您想四舍五入。
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
Run Code Online (Sandbox Code Playgroud)
假设您的意图是对科学中的统计数据进行传统的四舍五入,这是一个方便的包装方法,可以使round函数按预期工作,并且需要import额外的功能,例如Decimal。
>>> round(0.075,2)
0.07
>>> round(0.075+10**(-2*6),2)
0.08
Run Code Online (Sandbox Code Playgroud)
啊哈!因此,基于此我们可以创建一个函数...
def roundTraditional(val,digits):
return round(val+10**(-len(str(val))-1))
Run Code Online (Sandbox Code Playgroud)
基本上,这会在字符串中添加一个很小的值,以强制它在无法预料的情况下正确舍入,而在您无法预期的情况下,通常情况下它不会与round函数配合使用。添加一个方便的值是1e-Xwhere X是您要round在plus上尝试使用的数字字符串的长度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!\n"))
except ValueError:
print "\nYour 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 "\nYour Celsius value is " + answer + " C.\n"
main()
Run Code Online (Sandbox Code Playgroud)
...应该给您期望的结果。
您也可以使用十进制库来完成此操作,但是我建议的包装器更简单,在某些情况下可能更受欢迎。
编辑:感谢Blckknght指出,5条纹情况仅在此处的某些值出现。
为了避免 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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
500921 次 |
| 最近记录: |