Sling Academy
Home/Python/Python: Reverse the Order of Digits in a Number (2 Approaches)

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

Last updated: June 04, 2023

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.

Next Article: Python: How to format large numbers with comma separators

Previous Article: Python: Generate a Random Float between Min and Max (3 ways)

Series: Python – Numbers & Math Tutorials

Python

You May Also Like

  • Advanced DOM Interactions: XPath and CSS Selectors in Playwright (Python)
  • Automating Strategy Updates and Version Control in freqtrade
  • Setting Up a freqtrade Dashboard for Real-Time Monitoring
  • Deploying freqtrade on a Cloud Server or Docker Environment
  • Optimizing Strategy Parameters with freqtrade’s Hyperopt
  • Risk Management: Setting Stop Loss, Trailing Stops, and ROI in freqtrade
  • Integrating freqtrade with TA-Lib and pandas-ta Indicators
  • Handling Multiple Pairs and Portfolios with freqtrade
  • Using freqtrade’s Backtesting and Hyperopt Modules
  • Developing Custom Trading Strategies for freqtrade
  • Debugging Common freqtrade Errors: Exchange Connectivity and More
  • Configuring freqtrade Bot Settings and Strategy Parameters
  • Installing freqtrade for Automated Crypto Trading in Python
  • Scaling cryptofeed for High-Frequency Trading Environments
  • Building a Real-Time Market Dashboard Using cryptofeed in Python
  • Customizing cryptofeed Callbacks for Advanced Market Insights
  • Integrating cryptofeed into Automated Trading Bots
  • Monitoring Order Book Imbalances for Trading Signals via cryptofeed
  • Detecting Arbitrage Opportunities Across Exchanges with cryptofeed