How To Get Value After Decimal Point In Python

In Python, you often come across situations where you need to obtain the value after a decimal point in a given number. This tutorial will guide you through the different methods in which you can achieve this.

We will be exploring the following approaches:

  1. Using modulo operator %
  2. Using math.modf() function
  3. Using string manipulation

Step 1: Using modulo operator %

The modulo operator % returns the remainder after dividing the left-hand-side operand by the right-hand-side operand. By using the modulo operator with 1, you can get the value after the decimal point.

Output:

0.3449999999999993

Please note that the result might have some floating-point inaccuracies.

Step 2: Using math.modf() function

Python’s built-in math library provides the modf() function, which returns the fractional and integer parts of a floating-point number. The result is a tuple containing both parts. You can use this function to get the value after the decimal point.

Output:

0.34500000000000064

Please note that the result might have some floating-point inaccuracies.

Step 3: Using string manipulation

Another approach to get the value after the decimal point is by converting the floating-point number to a string and then manipulating the string. This method works with integer numbers and provides an exact result.

Output:

345.0

This method returns 345.0, which can now be easily used to perform any further operations you want.

Full Code

Here’s the full code for all the methods described above:

Conclusion

In this tutorial, we learned three different ways to get the value after the decimal point in a floating-point number in Python. The methods include using the modulo operator %, the math.modf() function, and string manipulation. You can choose the method that suits your needs best and provides the desired level of precision.