0

I have a Python script that produces the following output:

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

Please note the numbers 31.7, 31.8, 31.9.

The purpose of my script is to determine numeric palindromes, such as 1.01.

The problem with the script (reproduced below) is that it will evaluate numeric palindromes such as 1.1 as valid- however- that is not considered to be valid output in this situation.

Valid output needs to have exactly two decimal places.

How to enforce that the numeric output has at least two trailing decimal places, including trailing zeros?

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) )
halfer
  • 19,824
  • 17
  • 99
  • 186
smatthewenglish
  • 2,831
  • 4
  • 36
  • 72
  • Possible duplicate of [print float to n decimal places including trailing 0's](https://stackoverflow.com/questions/8568233/print-float-to-n-decimal-places-including-trailing-0s) – Zach Gates Sep 23 '17 at 03:17

4 Answers4

1

Try this instead of str(x):

twodec = '{:.2f}'.format(x)
John Zwinck
  • 239,568
  • 38
  • 324
  • 436
1

You can use the builtin format function. .2 refers to the number of digits, and f refers to "float".

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

Or:

if isPalindrome(candidrome):
    print("It's a Palindrome! %.2f" % candidrome)
Zach Gates
  • 4,045
  • 1
  • 27
  • 51
0

You can try this:

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]]
Ajax1234
  • 69,937
  • 8
  • 61
  • 102
0
x = ("%.2f" % x).replace('.','')
FluffyKitten
  • 13,824
  • 10
  • 39
  • 52
leyanpan
  • 433
  • 2
  • 9
  • Code-only answers are discouraged because they do not explain how they resolve the issue in the question. Consider updating your answer to explain what this does and how it addresses the problem - this will help not just the OP but others with similar issues. Please review [How do I write a good answer](https://stackoverflow.com/help/how-to-answer) – FluffyKitten Sep 23 '17 at 10:30