- 论坛徽章:
- 0
|
确定浮点数的保留位数的实现
提示:在统计学生的分数时,因为加权折算的结果不归正,所以要进行下处理再显示。一种是保留一位小数点,四舍五入;有时要设置三段式舍入。需要用python实现。
第一种:只保留一位。设x为要转换的数。最大分数情况为100.0
使用打印格式来实现。
>>> x=50.11
>>> print "5.1f" % x
50.1
>>> x="5.1f" %x
>>> x
50.1
第二种,按三段来舍入:
## if x=60.0~60.3 => 60.0
## if x=60.4~60.6 => 60.5
## if x=60.7~60.9 => 61.0
def trifloor(xy):
from math import floor, ceil, modf
x,y=modf(xy)
x="%3.1f"%x
if '0.0' >> trifloor(60.3)
60.0
>>> trifloor(60.4)
60.5
>>> trifloor(60.8)
61
三、如果小数位为0,则输出整数,否则输出小数
其中,sumscore ===> 为原始总分
score ===> 为原始得分
ret ===> 折算为百分制后的分数
def score_weighting(score, sumscore):
ret=score*100.0/sumscore
ret=trifloor(ret)
from math import floor
if ret==floor(ret):
return ("%d" % ret).strip()
else:
return ("%5.1f" % ret).strip()
本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u/13637/showart_694649.html |
|