Number line from 0 to 1 with fractions: Fractions on a number line (video)

Posted on

Fractions on a Number Line – Chart, Examples, and Diagrams

Graphing fractions on a number line helps us represent and compare fractions, like plotting whole numbers and integers. Fractions represent a part of a whole.

For representing a fraction on a number line, its two immediate whole numbers are marked at both ends. The total distance is divided into a total number of equal parts according to the value of the denominator. The numerator represents its distance from 0.

For example, in the fraction ${\dfrac{1}{3}}$, the numerator is 1, and the denominator is 3.

As we know that 0 < ${\dfrac{1}{3}}$ < 1, to put ${\dfrac{1}{3}}$ on a number line, we divide the region from 0 to 1 into 3 equal parts as the denominator is 3. Then, we move towards the right, starting from 0 based on the value of the numerator (here, 1). So we mark the 1st part starting from 0 as ${\dfrac{1}{3}}$.

Fractions on a Number Line 0 1

Here, ${\dfrac{1}{3}}$ is a unit fraction as it has 1 as its numerator.

As a number line represents values in ascending order, the values of the fractions also increase from left to right, like  ${\dfrac{1}{3}}$  <  ${\dfrac{2}{3}}$

As we know, while representing fractions on a number line, it appears between two integers. Thus, positive fractions lie at the right of 0 and between two positive integers, while the negative ones lie at the left of 0 and between two negative integers on a number line.

Number Line Positive and Negative Fractions

The above figure divides the region between each pair of successive integers into two equal parts. The positive fractions ${\dfrac{1}{2}}$, ${\dfrac{3}{2}}$  are found to the right of 0, while the negative fractions ${-\dfrac{1}{2}}$, ${-\dfrac{3}{2}}$ lie to the left of 0.

Representing Fractions on a Number Line

We can represent different types of fractions on a number line.

Proper Fractions

We can plot positive and negative proper fractions easily on a number line. As a proper fraction has its numerator always less than the denominator (comparing only the numeric values of the numerator and the denominator), a positive proper fraction always lies between 0 and 1 on a number line. Similarly, a negative proper fraction lies between (-1) and 0.

In the first diagram, we have shown plotting a positive proper fraction.

Similarly, we can represent a negative proper fraction on a number line by marking the points (-1) and 0 and dividing the region into equal parts based on the denominator. Then we move from right to left, starting from 0 according to the numerator.

For example, to show ${-\dfrac{5}{6}}$ on a number line, we mark the points (-1) and 0 on a number line.

Number Line Negative Proper Fraction Step 1

Then we divide the region from (-1) to 0 into 6 equal parts as the denominator is 6. Each part represents ${-\dfrac{1}{6}}$.

Number Line Negative Proper Fraction Step 2

Next, we move from right  to left  starting from 0 up to the 5th part as the numerator is 5 and mark it as ${-\dfrac{5}{6}}$

Number Line Negative Proper Fraction Step 3

Equivalent Fractions

Equivalent fractions are located at the same point on a number line because they represent the same value when it is reduced to its simplest form despite having different denominators and numerators.

Let us represent the equivalent fractions ${\dfrac{1}{3}}$, ${\dfrac{2}{6}}$, ${\dfrac{3}{9}}$ on a number line:

To plot ${\dfrac{1}{3}}$, we divide the region from 0 to 1 into 3 equal parts and mark the first part as ${\dfrac{1}{3}}$

To plot${\dfrac{2}{6}}$, we divide the region from 0 to 1 into 6 equal parts and mark the second part as ${\dfrac{2}{6}}$

Similarly to plot ${\dfrac{3}{9}}$ , we divide the region from 0 to 1 into 9 equal parts and mark the third part as ${\dfrac{3}{9}}$

Equivalent Fractions on a Number Line

Mixed Fractions

To represent a mixed fraction on a number line, we first identify its integer and proper fraction parts separately. Next, we mark those two integers on the number line between which the mixed fraction lies and move the number of steps right or left according to the proper fraction part.

Let us represent the mixed fraction ${4\dfrac{2}{5}}$ on the number line.

We get the fraction ${4\dfrac{2}{5}}$ by adding its integer part 4 and the proper fraction part ${\dfrac{2}{5}}$. To represent ${4\dfrac{2}{5}}$  on a number line, we first mark 4 and 5 on the number line as the integer part is 4 and ${4\dfrac{2}{5}}$ lies between 4 and 5.

Number Line Mixed Fraction Step 1

Next, we divide the above line segment into 5 equal parts, each representing ${\dfrac{1}{5}}$ and go to the proper fractional part (here${\dfrac{2}{5}}$) starting from 4.

Number Line Mixed Fraction Step 2

Thus we find the point representing ${4\dfrac{2}{5}}$ on the number line.

Improper Fractions

Representing improper fractions (positive and negative) on a number line is similar to graphing proper fractions. Positive improper fractions are always greater than 1 and lie between 1 and a positive integer. Similarly, negative improper fractions being less than (-1), lie between (-1) and a negative integer.

We can represent improper fractions on a number line by converting them into a mixed fraction and following the same procedure as above.

For example, to plot ${\dfrac{3}{2}}$ on a number line, we first convert it into a mixed fraction

${\dfrac{3}{2}}$ = ${1\dfrac{1}{2}}$

Then, we mark 1 and 2 on the number line as the integer part is 1. As we know, ${\dfrac{3}{2}}$ lies between 1 and 2; we divide the region from 1 to 2 into two equal parts, each representing ${\dfrac{1}{2}}$ and move towards the proper fraction, here ${\dfrac{1}{2}}$.

Fraction on a Number Line

Thus we find ${\dfrac{3}{2}}$ on a number line.

Solved Examples

Represent the fraction ${-8\dfrac{4}{7}}$  on the number line.


To represent ${-8\dfrac{4}{7}}$ on the number line, we follow the given steps:
In the fraction ${-8\dfrac{4}{7}}$, the integer part is (-8) and the proper fraction part is ${-\dfrac{4}{7}}$. As ${-8\dfrac{4}{7}}$ lies  between the integers (-8) and (-9), we divide the region from (-8) to (-9) in 7 equal parts and mark the 4th part starting from (-8).
Thus we get  ${-8\dfrac{4}{7}}$ on the number line.

Locate ${-\dfrac{9}{4}}$  on a number line.


We first convert the improper fraction ${-\dfrac{9}{4}}$ into a mixed fraction.
Again, ${-\dfrac{9}{4}}$ = ${-2\dfrac{1}{4}}$
Since ${-2\dfrac{1}{4}}$ lies between (-2) and (-3). Next we divide the region from (-2) to (-3) into 4 equal parts each representing ${-\left( \dfrac{1}{4}\right)}$ and go to the 1st part starting from (-2) to get the answer.
Thus we find ${-\dfrac{9}{4}}$ on the number line.
We have provided a printable fraction number line chart from 0 to 1 for your use.

We have provided a  printable fraction number line chart from 0 to 1 for your use.

Fraction Number Line Chart 0 to 1

Fractions Number Line — Thirds, Sixths, and Twelfths

  • Grades

    Grades:  3 — 6

Demonstrate the concept of thirds, sixths, and twelfths on a number line with a printable number line display and student reference sheets.

Fractions on a Number Line – No-Prep Teacher Tools

Ask any upper elementary/middle school teacher what the most challenging math topic to teach is…and you’ll most likely hear a chorus of FRACTIONS! They’re tough, and to make it more difficult, students transition from the standard visual models (pie, bar, etc. ) that they know and love to look at fractions on a number line. Step over onto the fourth and fifth-grade fraction railroad, dive into mixed numbers and equivalent fractions, and then the train falls off the track. Sometimes, they just don’t get it, and you must find a way to help them over the hurdle.

That’s where we come in. We’ve put together a visual model of fractions on a number line to help you and your students. This resource download includes an enlarged fraction number line for you to use as an instructional tool and two printable versions for your students to use during math lessons. With the visual model, students can identify the wholes, thirds, sixths, and twelfths as they appear between zero and two. We’ve also made sure to mark fractions with equivalents and note those in different colors. This model stretches across five pages and is easily assembled with some tape to connect the sheets.

Printable Fraction Number Lines for Thirds, Sixths, and Twelfths 

We’ve included two variations of the number line for your students to use as reference tools.

  • Version 1 is a fully complete number line, perfect for lamination and everyday use as a reference during lessons.
  • Version 2 is an entirely blank number line on which students record the fractions as they appear during instructional sessions. This version can be a note-taking tool, exit ticket, or formative assessment.

Download and Print Your Number Line With Fractions

This resource downloads as an editable Google Slides or quick-print PDF file. All you have to do is click the download button, print your file, and make your copies.

Lorin Davies, a teacher in Texas and Teach Starter collaborator contributed to this resource.

  • teaching resource

    Equivalent Fractions Bingo

    Match fraction models with an equivalent fraction with an exciting game of Bingo!

    1 page


    3 — 4

  • teaching resource

    Mixed Numbers — Fraction Model Match-Up

    Practice matching improper fractions, mixed numbers, bar models, and fraction number lines with this set of 36 match-up cards.

    12 pages


    4 — 5

  • teaching resource

    Equivalent Fractions – Dominoes

    Identify and match equivalent fractions with an exciting game of dominoes!

    1 page


    3 — 4

  • teaching resource

    Understanding Fractions – Exit Tickets

    Assess student understanding of basic fractions with this set of 24 math exit tickets.

    48 pages


  • teaching resource

    Equivalent Fractions – Worksheet Pack

    Use fraction models, strip diagrams, and number lines to determine equivalent fractions with this worksheet pack.

    1 page


    3 — 4

  • teaching resource

    Equivalent Fractions – Mystery Picture Worksheet

    Determine equivalent fractions while using the color guide to reveal a mystery image.

    2 pages


    3 — 4

  • teaching resource

    Equivalent Fractions – Clip Cards

    Determine an equivalent fraction that matches a fraction model with this set of 24 clip cards.

    1 page


    3 — 4

  • teaching resource

    Equivalent Fractions – Differentiated Math Mazes

    Practice your understanding of equivalent fractions with this set of differentiated math mazes.

    6 pages


    3 — 4

  • teaching resource

    Writing About Fractions- Task Cards

    Review fraction concepts and practice mathematical constructed response questions with a set of writing about fractions task cards.

    1 page


    4 — 5

  • teaching resource

    Fraction Partner Tasks — 4th Grade Fractions

    Encourage mathematical collaboration and discussion with a group of thirteen 4th-grade fractions partner activities.

    1 page


3 Peculiarities of Numbers in Python You Probably Didn’t Know About / Sudo Null IT News

If you have written Python code, chances are that you have used numbers in at least one of your programs. For example, they could be integers to indicate the index of a value in a list, or floating point numbers representing amounts in some currency.

But numbers in Python are much more than just their numeric values. Let’s talk about three features of numbers in Python that you may not be familiar with.

#1: Numbers have methods

In Python, almost everything is an object. One of the first objects that a beginner to Python learns about is str , which is used to represent strings. You may have come across string methods like .lower() , which returns a new string with all characters converted to lowercase:

 >>> "HELLO".lower()

Numbers are objects in Python, just like strings. They also have methods. For example, an integer can be converted to a byte string using the .to_bytes() :

 >>> n = 255
>>> n.to_bytes(length=2, byteorder="big")

The length parameter specifies the number of bytes to use when composing the byte string, and the byteorder parameter specifies the byte order. For example, setting parameter byteorder to "big" returns a byte string with the most significant byte first, while setting this parameter to "little" causes the low byte to come first.

255 is the maximum value that an 8-bit integer can take. Therefore, in our case, when calling the .to_bytes() method, you can easily use the parameter length=1 :

 >>> n.to_bytes(length=1, byteorder="big")

But if we write the number 256 into n and call . to_bytes() with parameter length=1 , an error will be thrown OverflowError :

 >>> n = 256
>>> n. to_bytes(length=1, byteorder="big")
Traceback (most recent call last):
File "", line 1, in 
OverflowError: int too big to convert 

You can convert a byte string to an integer using the method .from_bytes() of class int :

 >>> int.from_bytes(b'\x06\xc1', byteorder=" big")

Class methods are called using the name of the class, not its instance. That is why in the previous example method .from_bytes() is called by referring to int .

Curious fact : 1729 is the smallest positive number that can be expressed as the sum of the cubes of two positive numbers in two ways. A historical anecdote connects this number with the Indian mathematician Srinivasa Ramanujan, who told his mentor Gottfri Harold Hardy about it.

Hardy often visited Ramanujan when he was dying in the hospital in Putney. It was on one of these visits that the «incident» with the taxi number occurred. Hardy arrived in Putney by taxi, using his favorite means of transport. He entered the room where Ramanujan lay. Starting a conversation was always painfully difficult for Hardy, and he uttered his first sentence: «If I’m not mistaken, the number of the taxi in which I arrived is 1729. I think it’s a boring number.» To which Ramanujan immediately replied, “No, Hardy! Oh no! This is a very interesting number. It is the smallest number that can be represented as the sum of two cubes in two different ways.»

One way to represent the number 1729 as the sum of two cubes is 1 3 + 12 3 . Can you find the second way?

Floating point numbers also have methods. Perhaps the most useful of these is .is_integer() . It is used to check if a floating point number has a fractional part:

 >>> n = 2.0
>>> n.is_integer()
>>> n.is_integer()

Here is an interesting method .as_integer_ratio() . It, called on a floating point number, returns a tuple containing the numerator and denominator of the fraction representing that number:

 >>> n.as_integer_ratio()
(1, 2) 

However, due to a floating point representation error, sometimes this method returns unexpected results:

 >>> n = 0.1
>>> n.as_integer_ratio()
(3602879701896397, 36028797018963968) 

If necessary, you can call methods on numeric literals enclosed in parentheses:

 >>> (255).to_bytes(length=1, byteorder="big")
>>> (3.14).is_integer()

If parentheses are not used, an attempt to call a method on an integer literal will result in error SyntaxError . But when calling a method of a floating-point numeric literal, the absence of brackets, which is strange, will not lead to an error:SyntaxError: invalid syntax
>>> 3.14.is_integer()

A complete list of Python numeric type methods can be found in the documentation.

№2: numbers have a hierarchy

In mathematics, numbers have a natural hierarchy. For example, all natural numbers are integers, and all integers are rational. All rational numbers are real numbers, and all real numbers are complex numbers.

Similar considerations apply to the representation of numbers in Python. Here the «number tower» is expressed in terms of the abstract types contained in module numbers .

Number tower

All numbers in Python are instances of the class Number :

 >>> from numbers import Number
>>> # Integers are descendants of Number
>>> isinstance(1729, Number)
>>> # Floating point numbers are descendants of Number
>>> isinstance(3.14, Number)
>>> # Complex numbers are descendants of Number
>>> isinstance(1j, Number)

If you need to know if a Python value is numeric, but it doesn’t matter which numeric type it is, use the isinstance(value, Number) construct.

Python has four additional abstract types whose hierarchy, starting with the most general numeric type, looks like this:

  1. The Complex class is used to represent complex numbers. There is one built-in concrete type — complex .

  2. Class Real is a representation of real numbers. Its only built-in concrete type is float .

  3. Rational class represents rational numbers. Its only built-in concrete type is Fraction .

  4. Class Integral is used to represent whole numbers. It has two built-in concrete types — int and bool .

So, wait, are values ​​like bool really numbers? Yes, numbers. You can check this with the REPL:

 >>> import numbers
>>> # Complex numbers are descendants of Complex
>>> isinstance(1j, numbers.Complex)
>>> # Complex numbers are not heirs of Real
>>> isinstance(1j, numbers.Real)
>>> # Floats are descendants of Real
>>> isinstance(3.14, numbers.Real)
>>> # Floats are not derived from Rational
>>> isinstance(3.14, numbers.Rational)
>>> # Fractions objects are not Rational descendants
>>> from fractions import Fraction
>>> isinstance(Fraction(1, 2), numbers. Rational)
>>> # Fractions are not descendants of Integral
>>> isinstance(Fraction(1, 2), numbers.Integral)
>>> # Integers are descendants of Integral
>>> isinstance(1729, numbers.Integral)
>>> # Boolean values ​​are descendants of Integral
>>> isinstance(True, numbers.Integral)
>>> True == 1
>>> False == 0

All this, at first glance, looks quite normal. True, the order is somewhat violated by the fact that values ​​like bool are numbers.

Python oddity : since type bool belongs to class Integral (in fact it is a direct descendant of int ), with the values ​​ True and False you can do some pretty weird stuff.

For example, True can be used as an index to get the second element of an iterable. And if you divide the number by False , an error ZeroDivisionError will be generated.

Try "False"[True] and 1 / False in the REPL!

But if you take a closer look at the numeric types, there are a couple of oddities in the Python number hierarchy.

Decimal numbers do not fit into the hierarchy

As already mentioned, there are 4 concrete numeric types in the «number tower» of Python, corresponding to four abstract types: complex , float , Fraction and int . But Python also has a fifth numeric type, represented by the class Decimal . This type is used to accurately represent decimal numbers and to overcome the limitations of floating point arithmetic.

One might assume that numbers like Decimal are descendants of Real , but this is actually not the case:

 >>> from decimal import Decimal
>>> import numbers
>>> isinstance(Decimal("3.14159"), numbers.Real)

The only class whose descendant is Decimal is Number :

 >>> isinstance(Decimal("3.14159"), numbers.Complex)
>>> isinstance(Decimal("3.14159"), numbers.Rational)
>>> isinstance(Decimal("3. 14159"), numbers.Integral)
>>> isinstance(Decimal("3.14159"), numbers.Number)

It is logical that class Decimal is not a successor of Integral . To some extent, it also makes sense that Decimal is not a successor to Rational . But why is Decimal not a successor of Real or Complex ?

The answer lies in the CPython source code:

Decimal objects have all the methods defined in the Real class, but these objects should not be registered as children of Real because Decimal numbers do not interact with binary floating point numbers (for example, the result of Decimal(‘3.14’) + 2.71828 not defined). But it is expected that numbers whose classes are heirs of the abstract class Real are able to interact with each other (that is, R1 + R2 should be calculated if the numbers R1 and R2 are represented by types that are heirs of Real).

It turns out that the explanation of oddities comes down to implementation features.

Floats are strange creatures

Floats, on the other hand, implement the abstract base class Real . They are used to represent real numbers. But, due to the fact that computer memory is not an unlimited resource, floating point numbers are only finite approximations of real numbers. This leads to the possibility of writing «abnormal» code samples like this:0003

 >>> 0.1 + 0.1 + 0.1 == 0.3

Floating point numbers are stored in memory as binary fractions. This leads to some problems. For example, the fraction 1/3 does not have a finite decimal representation (there are an infinite number of triples after the decimal point). And the fraction 1/10 does not have a final representation as a binary fraction.

In other words, the number 0.1 cannot be perfectly represented in a computer unless that computer has infinite memory.

From a strictly mathematical point of view, all floating point numbers are rational numbers, except for float("inf") and float("nan") . But programmers use them as approximations of real numbers and treat them, for the most part, as real numbers.

Python oddity : float("nan") is a special floating point value representing «not a number». Such values ​​are often referred to as NaN . But since float is a numeric type, isinstance(float("nan"), Number) returns True .

It turns out that “not numbers” are numbers.

In general, floating point numbers are strange creatures.

#3: Python’s numeric type set can be extended

Python’s abstract numeric base type allows the programmer to create their own abstract and concrete numeric types.

Consider class 9 as an example0009 ExtendedInteger , which implements numbers of the form a+b√p, where a and b are integers and p is a prime number (note: the class does not enforce that the number p is simple ):

 import math
import numbers
class ExtendedInteger(numbers. Real):

def init(self, a, b, p = 2) -> None:
self.a = a
self.b = b
self.p = p
self._val = a + (b * math.sqrt(p))

return f"{}({self.a}, {self.b}, {self.p})"

def str(self):
return f"{self.a} + {self.b}√{self.p}"

return int(self._val)

def float(self):
return float(self._val)

def hash(self):
return hash(float(self._val))

return math.floor(self._val)

def ceil(self):
return math.ceil(self._val)

def round(self, ndigits=None):
return round(self._val, ndigits=ndigits)

def abs(self):
return abs(self._val)

deffloordiv(self, others):
return self._val // other

def rfloordiv(self, other):
return other // self._val

def truediv(self, others):
return self._val / other

def rtruediv(self, others):
return other / self._val

def mod(self, others):
return self._val % other

def rmod(self, others):
return other % self._val

def lt(self, others):
return self._val < other

def le(self, others):
return self._val <= other

def eq(self, others):
return float(self) == float(other)

def neg(self):
return ExtendedInteger(-self. a, -self.b, self.p)

def pos(self):
return ExtendedInteger(+self.a, +self.b, self.p)

def add(self, others):
if isinstance(other, ExtendedInteger):
# If both instances have the same p value,
# return a new instance of ExtendedInteger
if self.p == other.p:
new_a = self.a + other.a
new_b = self.b + other.b
return ExtendedInteger(new_a, new_b, self.p)
# Otherwise, return a float value
return self._val + other._val
# If other is an Integral value, add the value of other to the value of self.a
elif isinstance(other, numbers.Integral):
new_a = self.a + other
return ExtendedInteger(new_a, self.b, self.p)
# If other is a Real class value, return a float value
elif isinstance(other, numbers.Real):
return self._val + other._val
# If the type of other is unknown, let others decide
# about what to do in such a situation
return NotImplemented

def radd(self, others):
# Addition is commutative, so resorting to add
return self.add(other)

def mul(self, others):
if isinstance(other, ExtendedInteger):
# If both instances have the same p value,
# return a new instance of ExtendedInteger
if self. p == other.p:
new_a = (self.a * other.a) + (self.b * other.b * self.p)
new_b = (self.a * other.b) + (self.b * other.a)
return ExtendedInteger(new_a, new_b, self.p)
# otherwise return a float value
return self._val * other._val
# If other is an Integral value, multiply its a and b components by other
elif isinstance(other, numbers.Integral):
new_a = self.a * other
new_b = self.b * other
return ExtendedInteger(new_a, new_b, self.p)
# If other is a Real class value, return a float value
elif isinstance(other, numbers.Real):
return self._val * other
# If the type of other is unknown, let others decide
# about what to do in such a situation
return NotImplemented

def rmul(self, other):
# Multiplication is commutative, so resort to mul
return self.mul(other)

def pow(self, exponent):
return self._val ** exponent

def rpow(self, base):
return base ** self._val 

In order to ensure the correct implementation of the interface Real by a specific type, you need to create implementations of a set of methods whose names contain two underscores. We also need to think about how methods like .add() and .mul() interact with other types that inherit from Real .

Please note : the above example was not created with the expectation that it is complete or absolutely correct. Its purpose is to demonstrate to the reader the possibilities of working with numbers.

If you have an implementation of ExtendedInteger , you can do the following calculations:

 >>> a = ExtendedInteger(1, 2)
>>> b = ExtendedInteger(2, 3)
>>> a
ExtendedInteger(1, 2, 2)
>>> # Check if a is a descendant of Number
>>> isinstance(a, numbers.Number)
>>> # Check if a is a child of Real
>>> isinstance(a, numbers.Real)
>>> a * b
ExtendedInteger(14, 7, 2)
>>> float(a)

Python’s numeric type hierarchy is a fairly flexible structure. But of course, you should always be very careful about the implementation of types that inherit from Python’s built-in abstract base types. It is necessary to ensure that they work correctly with each other.

The Python documentation has some tips on implementing custom types that are worth reading for anyone who decides to get into creating their own numeric types. It will still be useful for such a person to get acquainted with the implementation Fraction .


Here are the three features of Python numbers that we discussed here:

  1. Numbers have methods, just like almost all other objects in Python.

  2. Numbers are hierarchical, even though their clear relationship is somewhat spoiled by the presence of types Decimal and float .

  3. Programmers can create their own numeric types that fit into Python’s numeric type hierarchy.

Maybe you learned from this material not only about these features of numbers, but also about something else that is useful to you.

Oh, come to work with us? 😏

We at wunderfund. io have been engaged in high-frequency algorithmic trading since 2014. High-frequency trading is a continuous competition between the best programmers and mathematicians around the world. By joining us, you will become part of this exciting fight.

We offer interesting and challenging tasks in data analysis and low latency development for enthusiastic researchers and programmers. Flexible schedule and no bureaucracy, decisions are quickly made and implemented.

Now we are looking for plus developers, pythonists, data engineers and ml-risers.

Join our team.

python — Testing for an integer—a condition for validating user input

To check if a string entered by the user is an integer , you can use int in a try/except, in a similar way as shown in the answer to the question «Python 3 User-entered fractional check recommended by @Alex.B, replacing float by int as @gil9red suggested and @slippyk explicitly showed:

 def isint(s):
        return True
        return False


 >>> isint('10')
>>> isint('a') # not a decimal digit
>>> isint('²') # superscript
>>> isint('১') # Bengali (Unicode)

This can break if the input is not a string, eg:

 >>> isint(0. 5) # XXX doesn't work for floats
>>> 0.5 .is_integer()
>>> from numbers import Integral
>>> isinstance(0.5, Integral)
>>> isinstance(123, Integral)
>>> isinstance(1., Integral) # XXX float
>>> 1..is_integer() # but an integer value
>>> from fractions import Fraction
>>> isint(Fraction(1, 2)) # XXX doesn't work for fractions
>>> isinstance(Fraction(1, 2), Integral)
>>> isinstance(Fraction(1), Integral) # XXX fraction
>>> Fraction(1) == 1 # even if it's an integer

See How to check if a float value is a whole number.

If you want to check that the given string contains only decimal digits and nothing else (for example, there are no '+' , '-' , ' ' , '\n' characters in it) , then you can use str.isdecimal :

 >>> '123'.isdecimal()
>>> '+123'.isdecimal()
>>> isint('+123')
>>> isint(' 123\n')
>>> '123\n'.isdecimal()

isdecimal() can be used to sort filenames containing numbers in «natural» order (like Windows Explorer).

By alexxlab

Similar Posts