Python: Reverse the Order of Digits in a Number (2 Approaches)

Updated: June 4, 2023 By: Khue Post a comment

This concise and straight-to-the-point article brings to the table two different ways to reverse the order of digits in a given number (integer or float) in Python.

Using string manipulation

The steps to get the job done are:

  1. Convert the number to a string using the str() function.
  2. Reverse the string using slicing with a step of -1, which can be done by using [::-1].
  3. If the number was a float, remove the trailing zeros using the rstrip("0") method (optional).
  4. Convert the reversed string back to a number using the int() or float() function.

Code example:

number = 2023.2024
number_str = str(number)
reversed_str = number_str[::-1].rstrip("0")
reversed_number = int(reversed_str) if reversed_str.isdigit() else float(reversed_str)

print(reversed_number)
# Output: 4202.3202

In case you need to perform this task many times, defining a function is more convenient:

def reverse_number(number):
    number_str = str(number)
    reversed_str = number_str[::-1].rstrip("0")
    reversed_number = int(reversed_str) if reversed_str.isdigit() else float(reversed_str)
    return reversed_number

This technique is simple and easy to understand, but it won’t work with negative numbers. This limitation will be eliminated in the following method.

Using mathematical operations

The idea can be explained as shown below:

  1. Check if the number is negative using the math.copysign() function from the math module. If it is, store the sign for later use.
  2. Take the absolute value of the number using the abs() function.
  3. Reverse the number using mathematical operations:
    1. For integers, use a while loop and repeatedly divide the number by 10 while updating the reversed number by multiplying it by 10 and adding the remainder.
    2. For floats, convert the number to a string, reverse the string, and convert it back to a float.
  4. If the original number was negative, multiply the reversed number by -1 to restore the sign.

Code example:

import math

# Define a function that takes in a number and reverses it
# This function can handle integers and floats (negative and positive)
def reverse_number(number):
    negative = math.copysign(1, number) == -1
    number = abs(number)

    if isinstance(number, int):
        reversed_num = 0
        while number > 0:
            reversed_num = (reversed_num * 10) + (number % 10)
            number //= 10
    else:  # float
        number_str = str(number)
        reversed_str = number_str[::-1]
        reversed_num = float(reversed_str)

    return -reversed_num if negative else reversed_num

# Test it out
print(reverse_number(123))
print(reverse_number(-123))
print(reverse_number(123.45))
print(reverse_number(-123.45))

Output:

321
-321
54.321
-54.321

This method is a bit more complicated, but it overcomes the weakness with negative numbers of the first method.