Get integer part python

How to Get the Integer Part of a Decimal Number in Python?

In Python, you can get the integer part of a decimal number in the following ways:

Using int()

You can use the int() method to truncate floating point numbers towards zero, discarding the fractional component of a number and returning only the integer part.

print(int(10 / 3)) # 3 print(int(-10 / 3)) # -3 print(int(10 / -3)) # -3 print(int(3.333)) # 3 print(int(-3.333)) # -3
print(int(5 / 2)) # 2 print(int(-5 / 2)) # -2 print(int(5 / -2)) # -2 print(int(2.5)) # 2 print(int(-2.5)) # -2
print(int(10 / 1)) # 10 print(int(-10 / 1)) # -10 print(int(10 / -1)) # -10 print(int(10.0)) # 10 print(int(-10.5)) # -10

Using math.floor() and math.ceil()

  • Use math.floor() to round down positive integers, and;
  • Use math.ceil() to round up negative integers.

Doing so would truncate a floating point number towards zero. You can implement it, for example, like so:

import math def trunc(num): return math.floor(num) if (num > 0) else math.ceil(num)

You can also implement this using only the math.floor() method like so:

import math def trunc(num): unsigned_num = math.floor(abs(num)) return -unsigned_num if (num < 0) else unsigned_num

Similarly, you can implement this using only the math.ceil() method like so:

import math def trunc(num): unsigned_num = math.ceil(-abs(num)) return unsigned_num if (num < 0) else -unsigned_num

Using any of these would yield the same result (as you can see in the examples below):

print(trunc(10 / 3)) # 3 print(trunc(-10 / 3)) # -3 print(trunc(10 / -3)) # -3 print(trunc(3.333)) # 3 print(trunc(-3.333)) # -3
print(trunc(5 / 2)) # 2 print(trunc(-5 / 2)) # -2 print(trunc(5 / -2)) # -2 print(trunc(2.5)) # 2 print(trunc(-2.5)) # -2
print(trunc(10 / 1)) # 10 print(trunc(-10 / 1)) # -10 print(trunc(10 / -1)) # -10 print(trunc(10.0)) # 10 print(trunc(-10.5)) # -10

Hope you found this post useful. It was published 02 Jan, 2023 . Please show your love and support by sharing this post.

Источник

Get integer part python

Last updated: Feb 20, 2023
Reading time · 4 min

banner

# Table of Contents

# Split a Float into Integer and Decimal parts in Python

Use the math.modf() method to split a number into integer and decimal parts.

The math.modf() method returns the fractional and integer parts of the provided number.

Copied!
import math my_num = 1.3588 result = math.modf(my_num) print(result) # 👉️ (0.3588, 1.0) print(result[0]) # 👉️ 0.3588 print(result[1]) # 👉️ 1.0

split float into integer and decimal parts

You can also use unpacking to assign the decimal and integer parts to variables.

Copied!
import math my_num = 1.3588 dec, integer = math.modf(my_num) print(dec) # 👉️ 0.3588 print(integer) # 👉️ 1.0

We used the math.modf() method to split a number into integer and decimal parts.

The math.modf method returns the fractional and integer parts of the provided number.

# The fractional and integer parts are of type float

The fractional and integer parts carry the sign of the provided number and are floats.

Copied!
import math my_num = -1.3588 result = math.modf(my_num) print(result) # 👉️ (-0.3588, -1.0) print(result[0]) # 👉️ -0.3588 print(result[1]) # 👉️ -1.0 # ----------------------------------------- # ✅ unpack decimal and integer values dec, integer = result print(dec) # 👉️ -0.3588 print(integer) # 👉️ -1.0

the fractional and integer parts are of type float

Notice that both of the values in the tuple are floats.

Читайте также:  Blockquote in html code

# Converting the integer part to an int after splitting

Copied!
import math my_num = 1.3588 result = math.modf(my_num) print(result) # 👉️ (0.3588, 1.0) dec = result[0] print(dec) # 👉️ 0.3588 integer = int(result[1]) print(integer) # 👉️ 1

converting the integer part to an int after splitting

Alternatively, you can use the % operator and floor division // .

# Split a number into integer and decimal parts using modulo operator

This is a two-step process:

  1. Use floor division to get the integer part of the number by dividing by 1 , e.g. num // 1 .
  2. Use the modulo % operator to get the fractional part by getting the remainder after dividing by 1 , e.g. num % 1 .
Copied!
my_num = -1.3588 dec = my_num % 1 print(dec) # 👉️ 0.3588 integer = my_num // 1 print(integer) # 👉️ 1.0

The modulo (%) operator returns the remainder from the division of the first value by the second.

When we use the modulo operator to divide a number by 1 , the remainder is the fractional part.

Copied!
print(1.3588 % 1) # 👉️ 0.3588

You can use floor division to get the integer part of a number.

Copied!
my_num = -1.3588 integer = my_num // 1 print(integer) # 👉️ 1.0 dec = my_num % 1 print(dec) # 👉️ 0.3588

The result of using the floor division // operator is that of a mathematical division with the floor() function applied to the result.

Dividing a number by 1 and rounding down, gives us the integer part of the number.

However, if you decide to use this approach, note that it doesn't handle negative numbers as you would expect.

Copied!
my_num = -1.3588 dec = my_num % 1 print(dec) # 👉️ 0.6412 integer = my_num // 1 print(integer) # 👉️ -2.0

If you have to handle negative numbers, use the math.modf() method instead.

# Split a number into integer and decimal parts using divmod

You might also see examples online that use the divmod() function.

However, note that divmod() also doesn't handle negative numbers in a way you would expect.

Copied!
my_num = 1.3588 result = divmod(my_num, 1) print(result) # 👉️ (1.0, 0.3588) integer = int(result[0]) print(integer) # 👉️ 1 dec = result[1] print(dec) # 👉️ 0.3588

The divmod function takes two numbers and returns a tuple containing 2 values:

  1. The result of dividing the first argument by the second.
  2. The remainder of dividing the first argument by the second.

However, the divmod() function also doesn't handle negative numbers in a way that suits our use case.

Copied!
my_num = -1.3588 result = divmod(my_num, 1) print(result) # 👉️ (-2.0, 0.6412) integer = int(result[0]) print(integer) # 👉️ -2 dec = result[1] print(dec) # 👉️ 0.6412

For this reason, you should use the math.modf() method when you have to split a number into integer and decimal parts.

# Subtracting integers from floats and accuracy

You can also split a floating-point number to an integer by:

  1. Converting the float to an integer (to drop the decimal).
  2. Subtracting the integer from the float to get the decimal part.
Copied!
a_float = 1.03588 integer = int(a_float) print(integer) # 👉️ 1 dec = a_float - integer print(dec) # 👉️ 0.03587999999999991

However, notice that you might get surprising results when subtracting from a floating-point number.

Читайте также:  Php расширение ioncube как включить

The resulting number cannot be represented in binary, so the precision is lost.

This might or might not suit your use case.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.

Источник

Want to seperate the integer part and fractional part of float number in python [duplicate]

I am Working on Converting the value of foot to inches where 1 foot = 12 inches. I am calculating the height of person in inches. ex. 5.11 a person of height 5 foots and 11 inches means total 71 inches. Is there any way in Python so i can separate the int part & float part of float number for further calculations ? any suggestions are welcome.

@AndrewWalker: Except in this case, we have an XY problem where the OP should not have a number in the first place

3 Answers 3

To get the integer part of a float use the built-in int() function:

To separate the float part subtract the float with the integer:

Or you could get the modulus (which is the float part) of the float with 1:

>>> 5.1 % 1 0.09999999999999964 #use the round() function if you want 0.1 

For you, 5.11 is not a float. If it were, then it would mean 5.11 feet, which is 61.32 inches.

5.11 is a string containing two pieces of data and a separator - parse it like one! If you change the separator to the more conventional ' (i.e. 5'11 ), it becomes obvious it is not a single float:

raw = raw_input("Enter feet'inches") feet, inches = map(int, raw.split("'", 1)) 

Another way is to use the divmod (function or operator), using as denominator (divisor) the number 1:

>>> divmod(5.11, 1) (5.0, 0.11000000000000032) >>> 5.11.__divmod__(1.) (5.0, 0.11000000000000032) 

@Eric, I took a look but didn't find out. can you provide me a referece about why I should never invoke the magic function divmod directly?

@Eric, thanks! I know for a long time that isn't right to call a magic function directly, but sincerely, in my very humble opinion, it depends of the context, and I can't see a good reason to no call __divmod__ directly for a float. The divmod function doesn't do nothing special, (differently from len that throws an exception for certain kinds of errors).

I guess my point is that seeing a __method__ suggests "Something unusual is going on here". You're right though, it is sometimes ok - for example, it's the only way when using super : super(MyClass, self).__divmod__(other)

Источник

How to return the fractional part of a number? [closed]

Want to improve this question? Update the question so it focuses on one problem only by editing this post.

How can I get the fractional part of a number? For example, I have a list of floats num = [12.73, 9.45] and want to get only the numbers after the decimal point, 73 and 45 in this case. How do I go about doing this?

Please repeat on topic and how to ask from the intro tour. "Show me how to solve this coding problem?" is off-topic for Stack Overflow. You have to make an honest attempt at the solution, and then ask a specific question about your implementation. Stack Overflow is not intended to replace existing tutorials and documentation.

Читайте также:  Page Title

This website is no substitute for reading one of the (huge!) number of Python language tutorials available,

3 Answers 3

One approach is using pure(ish) maths.

The short answer:

num = [12.73, 9.45] [int((f % 1)*100) for f in num] >>> [73, 44] 

Explanation:

The modulo operator returns the remainder once whole division is complete (to over-simplify).

Therefore this, returns the decimal value; the fractional part of the number.

12.73 % 1 >>> 0.7300000000000004 

To get the decimal value as a integer, you can use:

Just wrap this in a loop for all required values . and you have the 'short answer' above.

num = [12.73, 9.45]; result = list(map(lambda x: int(str(x).split('.')[1]),num)) print(result) 

and want to get only the numbers after the period,

There is no such thing. Numbers don't have digits; the string representation of the numbers has digits. And even then, floating-point numbers are not precise; you may be shown 0.3 in one context and 0.30000000000000004 in another, for the same value.

It sounds like what you are actually after is the fractional part of the numbers. There are many ways to do this, but they all boil down the same idea: it is the result when you divide (as a floating-point number) the input by 1.

For a single value, it looks like:

fractional_part = value % 1.0 
# This built-in function performs the division and gives you # both quotient and remainder. integer_part, fractional_part = divmod(value, 1.0) 
import math fractional_part = math.fmod(value, 1.0) 
import math # This function is provided as a special case. # It also gives you the integer part. # Notice that the results are the other way around vs. divmod! fractional_part, integer_part = math.modf(value) 

To process each value in a list in the same way, use a list comprehension.

Источник

Get the fractional and integer parts with math.modf() in Python

The math.modf() function allows you to get both the fractional and integer parts of a number simultaneously.

For a function that returns the quotient and remainder, check out the following article on divmod() .

Get fractional and integer parts using math.modf()

The math.modf() function enables you to get both the fractional and integer parts of a number at once.

math.modf() returns a tuple in the format (fractional part, integer part) .

import math print(math.modf(1.5)) print(type(math.modf(1.5))) # (0.5, 1.0) # 

You can assign each part to a variable using unpacking. Both the fractional and integer parts are of the float data type.

f, i = math.modf(1.5) print(i) print(f) # 1.0 # 0.5 print(type(i)) print(type(f)) # # 

The sign of the parts will match that of the original value.

f, i = math.modf(-1.5) print(i) print(f) # -1.0 # -0.5 

math.modf() can also be applied to the int . Again, both the fractional and integer parts are float .

f, i = math.modf(100) print(i) print(f) # 100.0 # 0.0 

To check if a float is an integer (meaning the fractional part is 0), you can use the is_integer() method for float without obtaining the fractional part. See the following article for more information.

Get fractional and integer parts without math module

By applying int() to a floating-point number, you can get its integer part. Consequently, you can extract both the fractional and integer parts.

a = 1.5 i = int(a) f = a - int(a) print(i) print(f) # 1 # 0.5 print(type(i)) print(type(f)) # # 

Источник

Оцените статью