强制数字输出至少有两个尾随小数位,包括尾随零
Enforce that numeric output has at least two trailing decimal places, including trailing zeros
我有一个生成以下输出的 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.7
、31.8
、31.9
。
我的脚本的目的是确定数字回文,例如1.01
。
脚本的问题(转载如下)是它会将 1.1
等数字回文计算为有效- 然而- 即 not 在这种情况下被认为是有效输出。
有效输出需要恰好 两位 小数位。
如何强制数字输出至少有两位小数,包括尾随零?
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) )
试试这个而不是 str(x)
:
twodec = '{:.2f}'.format(x)
你可以试试这个:
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]]
x = ("%.2f" % x).replace('.','')
您可以使用内置的 format
函数。 .2
指位数,f
指"float"。
if isPalindrome(candidrome):
print("It's a Palindrome! " + format(candidrome, '.2f'))
或者:
if isPalindrome(candidrome):
print("It's a Palindrome! %.2f" % candidrome)
我有一个生成以下输出的 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.7
、31.8
、31.9
。
我的脚本的目的是确定数字回文,例如1.01
。
脚本的问题(转载如下)是它会将 1.1
等数字回文计算为有效- 然而- 即 not 在这种情况下被认为是有效输出。
有效输出需要恰好 两位 小数位。
如何强制数字输出至少有两位小数,包括尾随零?
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) )
试试这个而不是 str(x)
:
twodec = '{:.2f}'.format(x)
你可以试试这个:
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]]
x = ("%.2f" % x).replace('.','')
您可以使用内置的 format
函数。 .2
指位数,f
指"float"。
if isPalindrome(candidrome):
print("It's a Palindrome! " + format(candidrome, '.2f'))
或者:
if isPalindrome(candidrome):
print("It's a Palindrome! %.2f" % candidrome)