Python Print Float Without Decimal Points

Problem Formulation

  • Given a floating point number x = 123.456.
  • How to print the number without decimal remainder?
x = 123.456
print(x)
# Desired output: 123
# Real output: 123.456

Solution 1: int()

Python’s built-in function int(x) converts any float number x to an integer by truncating it towards 0. For example, positive int(1.999) will be truncated to 1 and negative int(-1.999) to -1.

>>> int(123.456)
123
>>> int(-123.456)
-123

To boost your skills, feel free to watch my explainer video on the int() function next:

Solution 2: round()

Python’s built-in function round(x), when called with a single float argument x, converts the float to an integer by rounding it up and down to the next integer. For example, int(1.999) will be rounded to 2 and int(-1.999) to -2.

>>> round(123.456)
123
>>> round(-123.456)
-123

To boost your skills, feel free to watch my explainer video on the round() function next:

Solution 3: Print Decimal and Non-Decimal Parts Separately

Given a string representing a floating point number, you can print the parts before and after the decimal point by splitting the string on the decimal point and converting the two parts to integers by using the int() built-in function in a list comprehension statement.

x = '123.456'
num, decimal = [int(part) for part in x.split('.')]

print(num)
# 123

print(decimal)
# 456

This snippet builds on four Python concepts you need to understand first:

Let’s explore the most important one, the list comprehension statement, in the following video!

Where to Go From Here?

Enough theory, let’s get some practice!

To become successful in coding, you need to get out there and solve real problems for real people. That’s how you can become a six-figure earner easily. And that’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?

Practice projects is how you sharpen your saw in coding!

Do you want to become a code master by focusing on practical code projects that actually earn you money and solve problems for people?

Then become a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.

Join my free webinar “How to Build Your High-Income Skill Python” and watch how I grew my coding business online and how you can, too—from the comfort of your own home.

Join the free webinar now!