2017-09-23 94 views
0

我有一个产生以下输出一个Python脚本:强制执行数字输出至少有两个尾随小数,包括尾随零

31.7 
31.71 
31.72 
31.73 
31.74 
31.75 
31.76 
31.77 
31.78 
31.79 
31.8 
31.81 
31.82 
31.83 
31.84 
31.85 
31.86 
31.87 
31.88 
31.89 
31.9 
31.91 

请注意编号31.731.831.9

我的脚本的目的是确定数字回文,如1.01

与(以下转载)脚本的问题是,它会评估数字回文,如1.1为有效─然而 - 这是认为在这种情况下,有效的输出。

有效输出需要精确到两个小数位数。

如何强制数字输出至少有两个尾随小数位,包括尾随零?

import sys 

# This method determines whether or not the number is a Palindrome 
def isPalindrome(x): 
    x = str(x).replace('.','') 
    a, z = 0, len(x) - 1 
    while a < z: 
     if x[a] != x[z]: 
      return False 
     a += 1 
     z -= 1 
    return True 

if '__main__' == __name__: 

    trial = float(sys.argv[1]) 

    operand = float(sys.argv[2]) 

    candidrome = trial + (trial * 0.15) 

    print(candidrome) 
    candidrome = round(candidrome, 2) 

    # check whether we have a Palindrome 
    while not isPalindrome(candidrome): 
     candidrome = candidrome + (0.01 * operand) 
     candidrome = round(candidrome, 2) 
     print(candidrome) 

    if isPalindrome(candidrome): 
     print("It's a Palindrome! " + str(candidrome)) 
+0

的可能的复制[打印浮到n位小数包括末尾的0](https://stackoverflow.com/questions/8568233/print-float-to-n-小数位 - 包括 - 尾 - 零) –

回答

1

您可以使用内置的format功能。 .2指的是数字的位数,而f指的是“浮点数”。

if isPalindrome(candidrome): 
    print("It's a Palindrome! " + format(candidrome, '.2f')) 

或者:

if isPalindrome(candidrome): 
    print("It's a Palindrome! %.2f" % candidrome) 
+0

这是否会将它变成一个字符串? –

+0

@ s.matthew.english:是的。像'格式(0.666666,'.2f')''会返回''0.67''。 –

+0

但我需要它作为一个浮点数,所以我可以管回到函数并使其成为回文 –

1

试试这个,而不是str(x)

twodec = '{:.2f}'.format(x) 
+0

我仍然看到有害的非尾随零点,就像这个'3.2' –

+0

没有 - 我的错误 - 这实际上是正确的 –

0

你可以试试这个:

data = """ 
    1.7 
    31.71 
    31.72 
    31.73 
    """ 
new_data = data.split('\n') 
palindromes = [i for i in new_data if len(i) > 3 and i.replace('.', '') == i.replace('.', '')[::-1]] 
0
x = ("%.2f" % x).replace('.','') 
+0

只有代码的答案是不鼓励的,因为它们没有解释他们如何解决问题中的问题。考虑更新你的答案,以解释它做了什么,以及它如何解决问题 - 这不仅有助于OP,而且还有其他类似问题。请回顾[如何写出一个好的答案](https://stackoverflow.com/help/how-to-answer) – FluffyKitten