How to get the decimal part of a number in Python

Learn how to get the decimal part of a number in Python. Explore different methods, real-world applications, and common debugging tips.

How to get the decimal part of a number in Python
Published on: 
Tue
Mar 17, 2026
Updated on: 
Tue
Mar 24, 2026
The Replit Team

In Python, you can isolate the decimal part of a number for tasks like financial calculations or data analysis. The language provides several straightforward methods to handle these fractional values efficiently.

You'll explore techniques that use the modulo operator (%) and dedicated functions. You will also discover practical tips, see real-world applications, and get advice to fix common errors with fractional numbers.

Using the % operator for the decimal part

number = 42.75
decimal_part = number % 1
print(f"The decimal part of {number} is {decimal_part}")--OUTPUT--The decimal part of 42.75 is 0.75

The modulo operator, %, is a clever tool for this task because it calculates the remainder of a division. When you use the expression number % 1, you're dividing the number by 1 and capturing what's left over.

The integer portion of your number divides cleanly by 1, leaving a remainder of zero. Therefore, the only part that remains is the decimal itself. It’s an elegant and efficient trick for isolating the fractional component of any floating-point number.

Common mathematical approaches

While the modulo operator is a clever approach, Python also provides more direct mathematical methods for isolating the fractional part of a number.

Extracting decimal part with math.modf()

import math
number = 123.456
fractional_part, integer_part = math.modf(number)
print(f"The decimal part of {number} is {fractional_part}")--OUTPUT--The decimal part of 123.456 is 0.456

The math.modf() function is purpose-built for separating a number into its components. It returns a tuple with two values: the fractional part and the integer part, in that specific order. This allows you to unpack them neatly into separate variables like fractional_part and integer_part.

A key detail is that both returned values are floats.

  • The fractional part comes first.
  • The integer part comes second.

Both parts also keep the sign of the original number, which makes math.modf() a predictable and robust choice for numerical operations.

Subtracting the integer part

number = 7.89
integer_part = int(number)
decimal_part = number - integer_part
print(f"The decimal part of {number} is {decimal_part}")--OUTPUT--The decimal part of 7.89 is 0.8900000000000006

Another intuitive way to get the decimal is by subtraction. You can convert the number to an integer with int(), which chops off everything after the decimal point. Subtracting this new integer from the original number leaves you with just the fractional value.

However, this method can introduce floating-point inaccuracies. Notice the output 0.8900000000000006 instead of a clean 0.89. This happens because:

  • Computers use binary to represent numbers, which can't always store decimal fractions perfectly.
  • This leads to tiny precision errors that are important to be aware of in your calculations.

Using the Decimal module for precision

from decimal import Decimal
number = Decimal('15.725')
decimal_part = number % 1
print(f"The decimal part of {number} is {decimal_part}")--OUTPUT--The decimal part of 15.725 is 0.725

When precision is critical, Python’s Decimal module is the right tool. It sidesteps the floating-point inaccuracies that can occur with standard floats because it represents decimal numbers exactly. This is especially useful in financial or scientific applications where small errors can have big consequences.

  • You initialize the Decimal object with a string, like Decimal('15.725'), to preserve its exact value from the start.
  • The modulo operator, % 1, works just as it does with floats but delivers a precise result without any rounding errors.

Advanced techniques

For more complex scenarios, you can turn to advanced tools like divmod(), regular expressions, and libraries such as numpy to extract decimal values.

Using divmod() for decimal extraction

number = 98.765
_, decimal_part = divmod(number, 1)
print(f"The decimal part of {number} is {decimal_part}")--OUTPUT--The decimal part of 98.765 is 0.765

The divmod() function is a Python built-in that handles division and modulo in a single call. It takes two numbers and returns a tuple with their quotient and remainder. When you use divmod(number, 1), you get the integer part and the fractional part.

  • The first value in the tuple is the whole number.
  • The second is the decimal remainder.

In the example, the underscore _ is a convention for a variable you don't intend to use. It effectively discards the integer part, letting you capture just the decimal_part.

Extracting decimals with regular expressions

import re
number = 3.14159
match = re.search(r'\.(\d+)', str(number))
decimal_part = float('0.' + match.group(1)) if match else 0.0
print(f"The decimal part of {number} is {decimal_part}")--OUTPUT--The decimal part of 3.14159 is 0.14159

Regular expressions offer a flexible way to handle numbers as text. You first convert the number to a string with str(), allowing the re module to process it. The pattern r'\.(\d+)' then searches for the decimal part.

  • The \. specifically targets the decimal point.
  • The (\d+) captures one or more digits that come after it.

If a match is found, match.group(1) extracts these captured digits. You then prepend '0.' to them and convert the resulting string back into a float to get the final decimal value.

Using numpy for numerical precision

import numpy as np
number = 5.678
decimal_part = np.modf(number)[0]
print(f"The decimal part of {number} is {decimal_part}")--OUTPUT--The decimal part of 5.678 is 0.678

For numerical work, the numpy library offers its own version of modf. The np.modf() function operates similarly to its counterpart in the math module, splitting a number into its fractional and integer components. It returns a tuple where the decimal part comes first.

  • You access this fractional value using the index [0].
  • The integer part is the second element in the tuple.

This shows how numpy’s powerful tools can be applied to single numbers, not just large datasets.

Move faster with Replit

Replit is an AI-powered development platform that transforms natural language into working applications. You can describe what you want to build, and its AI capabilities help bring your idea to life.

With Replit Agent, you can turn the concepts from this article into complete apps—with databases, APIs, and deployment—directly from a description. It can take the logic for isolating decimal values and build a fully functional tool around it.

  • Build a financial transaction ledger that separates whole units from fractional cents for precise accounting, similar to using the Decimal module.
  • Create a unit conversion utility that can take a value like 7.25 hours and correctly display it as 7 hours and 15 minutes by isolating the 0.25 portion.
  • Deploy a data analysis dashboard that identifies anomalies by examining the fractional parts of numerical data, a task where functions like math.modf() are essential.

Turn your own idea into a working application. Describe what you want to build and let Replit Agent write, test, and deploy the code for you.

Common errors and challenges

When working with fractional numbers, you might encounter precision issues, unexpected behavior with negative values, or type errors that can trip you up.

You've already seen how floating-point math can leave behind tiny, unwanted fractions. The built-in round() function is a practical fix. It lets you specify the number of decimal places you want to keep, effectively trimming any precision errors from your result and making your output clean.

Using the modulo operator (%) with negative numbers can also produce surprising results. For instance, -42.75 % 1 evaluates to 0.25, not the -0.75 you might expect. This happens because the result takes the sign of the divisor (1). If you need to handle negative values predictably, math.modf() is a safer bet since it preserves the original number's sign in the fractional part.

Finally, attempting to get the decimal part of a non-numeric value, such as a string, will raise a TypeError and halt your script. You can prevent this by validating your data first. A try-except block allows you to handle the error gracefully, while a function like isinstance() lets you confirm you're working with a number before the operation.

Handling floating-point precision with the round() function

Floating-point arithmetic can lead to small but significant inaccuracies. Because computers represent decimal numbers in binary, simple operations don't always produce the exact result you'd expect. This can cause problems when you compare fractional values for equality.

The following code demonstrates this issue. It compares the result of 0.1 + 0.2 with 0.3 after isolating their decimal parts. Notice how the comparison fails, highlighting the tiny precision error that arises from the calculation.

value1 = 0.1 + 0.2
value2 = 0.3
decimal1 = value1 % 1
decimal2 = value2 % 1
print(f"Are the decimal parts equal? {decimal1 == decimal2}")
print(f"{decimal1} vs {decimal2}")

The comparison decimal1 == decimal2 returns False because the binary representation of 0.1 + 0.2 isn't identical to 0.3. This tiny difference makes direct equality checks unreliable. The following code shows a practical way to fix this.

value1 = 0.1 + 0.2
value2 = 0.3
decimal1 = round(value1 % 1, 10)
decimal2 = round(value2 % 1, 10)
print(f"Are the decimal parts equal? {decimal1 == decimal2}")
print(f"{decimal1} vs {decimal2}")

The fix is to use the round() function. By rounding both results to a set number of decimal places, you eliminate the tiny precision errors left over from the calculation. This standardizes the values, allowing the comparison decimal1 == decimal2 to return True as expected. It’s a crucial step whenever you're checking if two floats are equal, especially after they’ve been part of an arithmetic operation.

Dealing with negative numbers when using the % operator

The modulo operator (%) can be tricky with negative numbers. Instead of returning a negative decimal, the expression negative_number % 1 produces a positive result because the remainder inherits the sign of the divisor (1). The code below shows this unexpected behavior.

negative_number = -7.25
decimal_part = negative_number % 1
print(f"The decimal part of {negative_number} is {decimal_part}")

The code returns 0.75, which is the positive remainder of the division. If your goal is to get -0.25 and preserve the number's original sign, you'll need a different approach. The following example shows a reliable alternative.

negative_number = -7.25
decimal_part = abs(negative_number) % 1
print(f"The decimal part of {negative_number} is {decimal_part}")

A simple fix is to use the abs() function before the modulo operator. This converts the number to its positive equivalent, so abs(-7.25) becomes 7.25. Then, applying % 1 correctly isolates the decimal part as 0.25. This method is perfect when you need the magnitude of the fractional part and don't need to preserve the original negative sign. It ensures you get a consistent, positive decimal value every time.

Preventing errors with proper type checking

Trying to get the decimal part of a non-numeric value, like a string, will trigger a TypeError. This error stops your script because an operation like the modulo operator (%) can't work on text. The following code shows what happens when you don't check your data types first.

def get_decimal_part(value):
return value % 1

values = [42.5, "3.14", 7]
for val in values:
print(f"Decimal part of {val}: {get_decimal_part(val)}")

The get_decimal_part() function works for numbers but fails when the loop passes it the string "3.14". The script can't apply the modulo operator (%) to text, which raises an error. The following example shows how to handle this gracefully.

def get_decimal_part(value):
try:
return float(value) % 1
except (ValueError, TypeError):
return f"Error: {value} is not a valid number"

values = [42.5, "3.14", 7]
for val in values:
print(f"Decimal part of {val}: {get_decimal_part(val)}")

The solution is to wrap the logic in a try-except block. It first attempts to convert any input to a number with float(value). If the conversion fails because the value isn't numeric, the except (ValueError, TypeError) block catches the error and returns a helpful message. This defensive approach prevents your script from crashing, which is essential when you're working with data from uncertain sources like user input or external files.

Real-world applications

Isolating decimal values is more than a technical exercise; it’s a key skill for solving practical problems in finance and data analysis.

Calculating tip amounts with decimal rounding

In a common scenario like calculating a restaurant tip, you can isolate the decimal portion of the calculated amount to round the final payment to a convenient value, such as the nearest quarter.

bill_amount = 42.75
tip_percentage = 18
tip_amount = bill_amount * (tip_percentage/100)

# Round tip to nearest quarter using decimal part
decimal_part = tip_amount % 1
quarters = round(decimal_part * 4) / 4
rounded_tip = int(tip_amount) + quarters

print(f"Bill: ${bill_amount}, Calculated tip: ${tip_amount:.2f}")
print(f"Rounded tip to nearest quarter: ${rounded_tip:.2f}")

This code first calculates a standard tip_amount. The interesting part is how it adjusts this value for convenience.

  • It isolates the fractional part of the tip using the modulo operator, % 1.
  • This decimal is then converted into a quarter-dollar equivalent by multiplying by 4 and using round().
  • Dividing the result by 4 gives a new decimal snapped to an increment like .00, .25, .50, or .75.

Finally, this adjusted decimal is added back to the tip's integer part, creating a final rounded_tip that's simpler to pay.

Detecting patterns with decimal parts in financial data

In financial analysis, the decimal parts of transaction amounts can reveal unusual patterns, such as a high frequency of whole numbers that might suggest manual data entry or even fraud.

import numpy as np

# Sample financial transactions data
transactions = np.array([142.00, 97.00, 213.45, 32.00, 450.00, 78.92])

# Extract decimal parts to analyze rounding patterns
decimal_parts = transactions % 1
zero_decimal_count = sum(1 for d in decimal_parts if d == 0)
zero_decimal_ratio = zero_decimal_count / len(transactions)

print(f"Transactions: {transactions}")
print(f"Proportion of whole-number amounts: {zero_decimal_ratio:.2f}")
print(f"Possible manual entry detected: {zero_decimal_ratio > 0.5}")

This code uses the numpy library to efficiently analyze financial transactions. It leverages a vectorized operation, transactions % 1, to extract the decimal part from every number in the array simultaneously, which is much faster than looping.

The analysis then focuses on identifying specific data characteristics:

  • It counts how many transactions are whole numbers by checking for decimal parts equal to 0.
  • It calculates the ratio of these whole-number amounts to the total number of transactions.

This approach is great for quickly profiling a dataset to understand its composition.

Get started with Replit

Put these techniques into practice by building a real tool. Describe what you want, like “a tip calculator that rounds to the nearest quarter” or “a script that analyzes transaction data for non-standard decimal values.”

Replit Agent will write the code, test for errors, and deploy your application from your description. Start building with Replit.

Get started free

Create and deploy websites, automations, internal tools, data pipelines and more in any programming language without setup, downloads or extra tools. All in a single cloud workspace with AI built in.

Get started for free

Create & deploy websites, automations, internal tools, data pipelines and more in any programming language without setup, downloads or extra tools. All in a single cloud workspace with AI built in.