2015-06-26 47 views
0

我正在寻找Jython中的功能,即浮点输出只有在不是整数时才有小数点。只有在需要时浮点数的Jython小数位数

我发现:

>>> x = 23.457413902458498 
>>> s = format(x, '.5f') 
>>> s 
'23.45741' 

>>> y=10 
>>> format(y, '.2f') 
'10.00' 

在这种情况下,我想有只

'10' 

你能帮助我吗?

谢谢你的帮助!

回答

1

这将在Jython的2.7工作,其中x是要格式化您的浮动和其他后的值将设置你的小数点后的位数:

"{0:.{1}f}".format(x, 0 if x.is_integer() else 2) 
1

尝试“G”(表示“一般”)为浮点数格式规范(docs):

>>> format(23.4574, '.4g') 
'23.46' 
>>> format(10, '.4g') 
'10' 

注意,给出的数字是不小数点后的数字,它的精度(显著位数),这就是为什么在第一实施例保持4位从输入。

如果要指定小数点后的数字,但除去尾随零,直接实现这一点:

def format_stripping_zeros(num, precision): 
    format_string = '.%df' % precision 
    # Strip trailing zeros and then trailing decimal points. 
    # Can't strip them at the same time otherwise formatting 10 will return '1' 
    return format(num, format_string).rstrip('0').rstrip('.') 

>>> format_stripping_zeros(10, precision=2) 
'10' 
>>> import math 
>>> format_stripping_zeros(math.pi, precision=5) 
'3.14159' 
相关问题