Python Jython仅在需要时才使用小数位数表示浮动

Python Jython仅在需要时才使用小数位数表示浮动,python,jython,Python,Jython,我正在搜索Jython中的功能,即浮点的输出只有在不是整数时才有小数点 我发现: >>> x = 23.457413902458498 >>> s = format(x, '.5f') >>> s '23.45741' 但是 在这种情况下,我只希望 '10' 你能帮我吗 谢谢你的帮助 这将在Jython 2.7中起作用,其中x是要格式化的浮点值,else后面的值将设置小数位数: "{0:.{1}f}".format(x, 0 if x.i

我正在搜索Jython中的功能,即浮点的输出只有在不是整数时才有小数点

我发现:

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

在这种情况下,我只希望

'10'
你能帮我吗


谢谢你的帮助

这将在Jython 2.7中起作用,其中x是要格式化的浮点值,else后面的值将设置小数位数:

"{0:.{1}f}".format(x, 0 if x.is_integer() else 2)
尝试浮动()的“g”(表示“通用”)格式规范:

请注意,给定的数字不是小数点后的数字,而是精度(有效位数),这就是第一个示例保留输入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'
>>> format(23.4574, '.4g')
'23.46'
>>> format(10, '.4g')
'10'
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'