Truncate float in Python

Truncate float in Python

Truncating a floating-point number is a widely used practice and helps in making the calculations and results easier. The process of truncating a float can be tackled in two ways, one by removing the excess and unnecessary digits or the other by simply rounding the number.

This article focuses on the different ways available to truncate float in Python.

What is a float in Python?

A float is one of the two number types provided in Python and is a data type that is utilized for storing a floating-point number or a number that contains a decimal point.

How to truncate float in Python?

Using f-strings to truncate float in Python.

String formatting provides a medium for loads of customizations on string variables in the python code. The customizations can be manually chosen and done by the programmer. We use the % sign, which is commonly regarded as the interpolation operator for implementing string formatting in Python.

The f-strings were introduced starting from the version Python 3.6 and provide a fresh and improved approach to carry out the process of string formatting. The f-strings are known to be faster and more concise than their older counterparts.

The following code uses f-strings to truncate float in Python.

The above code provides the following output:

1.26

We should note that the output here is 1.26, which means that the number has been rounded off automatically. The f-strings are a smart and efficient way of string formatting and thus, enable the automatic rounding off of the given number.

Explanation:
  • As f-strings are used on strings, the given floating-point number is converted to a string.
  • Then, we look at the syntax f"{field_name:[.precision][type]}" and specify the given number in the field_name, and the desired number places for truncating in place of the precision space respectively.
  • Then, the float() function is called with the corresponding f-string as an argument to the function.
  • The received float variable is then displayed as the output.

Using the int() function to truncate float in Python.

We can make use of the int() function to truncate float in Python. However, its working is not all straightforward and is explained below.

To simply drop the unnecessary characters from the floating-point number, we will multiply the given number with 10**x with x being the number of digits after the decimal place that we want to be left with at the end. The number is then divided with the same value 10**x and converted back to float.

The following code uses the int() function to truncate float in Python.

The above code provides the following output:

1.25
Explanation:
  • A user-defined function is created, where the given float is first converted to an integer and is multiplied with 10**x as explained above.
  • Then, it is divided by the same value.
  • This resulting integer variable is then converted back to float.
  • The output is then displayed by calling out the created function.

Using the str() function to truncate float in Python.

In this method, the float is first converted to a string and is then worked upon.

We simply search for a decimal point in the resultant string after converting the float to a string variable. If the decimal point exists, we specify x which are the digits to be saved after this decimal place.

The following code uses the str() function to truncate float in Python.

The above code provides the following output:

1.25
Explanation:
  • A user-defined function is created, and the float value is converted to a string.
  • The resultant string temp is checked as to whether it contains a decimal place or not.
  • If it does, then with the help of the try...catch statements, the unnecessary decimal places are removed.
  • The string is finally converted back to float at the end of the function.
  • The result is displayed by calling the created function.

Using the round() function to truncate float in Python.

The round() function is a predefined function that is generally utilized to round off any given floating-point number. It takes in two parameters, the number which is to be operated on, and the decimal places that we want to round the number off to.

The following code uses the round() function to truncate float in Python.

The above code provides the following output:

1.26

We should note that unlike the previous two methods mentioned above, this method rounds off the given floating-point number along with carrying out the process of truncating it.

That’s all about how to truncate float in Python.

Was this post helpful?


import_contacts

You may also like:

Related Posts

  • 01 February

    Write Binary Files in PowerShell

    Table of ContentsUsing Add-Content CmdletUsing the [IO.File]::WriteAllBytes() MethodUsing FromBase64CharArray() with Add-Content Using Add-Content Cmdlet Use the Add-Content cmdlet to write binary files in PowerShell. [crayon-63da9666571a6825153809/] This script created a new file named test.bin in the current working directory and wrote the binary data to the file. The script will overwrite the existing file with the […]

  • 01 February

    What Does Percent(%) Mean in PowerShell

    Table of ContentsUsing Percent (%) in Different ContextsUse Percent(%) as an alias of the ForEach-Object cmdlet in PowerShellUse percent (%) as the Modulus Operator in PowerShellUse percent(%) as an assignment operator (%=) in PowerShell Using Percent (%) in Different Contexts Typically the % character is for mod functionality. But in PowerShell, it’s an alias for […]

  • 28 January

    PowerShell – Get Number of Lines in CSV File

    Table of ContentsUsing Get-Content CmdletUsing Import-Csv CmdletUsing Get-ChildItem with Foreach-Object Using Get-Content Cmdlet The Get-Content cmdlet can be used in the following ways to get the number of lines in the specified .csv file: Get-Content cmdlet with .Length property Get-Content cmdlet with .Count property Get-Content cmdlet with .ReadCount property Get-Content cmdlet with Measure-Object cmdlet and […]

  • Read CSV file in PowerShell
    28 January

    Read CSV File in PowerShell

    Table of ContentsUsing the Import-Csv CmdletUsing the ConvertFrom-Csv CmdletUse the ConvertFrom-Csv Cmdlet with the Pipe (|) OperatorUse the ConvertFrom-Csv Cmdlet with the -InputObject Parameter Using the Import-Csv Cmdlet To read a CSV file in PowerShell, use the Import-Csv cmdlet. [crayon-63da96665791e793048157/] [crayon-63da966657925378045653/] PowerShell provides several cmdlets that allow us to work with CSV files: Import-Csv ConvertFrom-Csv […]

  • Read File into String in PowerShell
    27 January

    Read File into String in PowerShell

    Table of ContentsUsing the Get-Content CmdletUse the Get-Content Cmdlet to Read a Single FileUse the Get-Content Cmdlet with forreach loop to Read Multiple FilesUsing [System.IO.File]::ReadAllText() MethodUse the [System.IO.File]::ReadAllText() Method with foreach loop to Read Multiple FilesUsing the Variable Notation with the Out-String Cmdlet Using the Get-Content Cmdlet We can use the Get-Content cmdlet to read […]

  • Get String between two characters in JavaScript
    27 January

    Get String Between Two Characters in JavaScript

    Table of ContentsUsing substring() MethodUsing slice() MethodUsing split() MethodUsing substr() Method 💡TL;DR Use the substring() method to get String between two characters in JavaScript. [crayon-63da966657dd7941725127/] [crayon-63da966657ddd514754855/] Here, we got String between , and ! in above example. Using substring() Method Use the substring() method to extract a substring that is between two specific characters from […]

Leave a Reply

Your email address will not be published. Required fields are marked *

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.