Search code examples
pythonfloating-pointprecisiondecimal-point

Enforce that numeric output has at least two trailing decimal places, including trailing zeros


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) )

Solution

  • 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)