## Scala Vs Kotlin

Rated 4.5/5 based on 19 customer reviews

# Scala Vs Kotlin

8K

Ever-changing requirements in coding have always been happening, ones that cause programmers to change their minds about using the appropriate programming language and tools to code. Java has been there for a long time, a really long time, 24 years ago. It is relatively easy to use, write, compile, debug, and learn than other programming languages.

However, its certain inhibitions like slow performance, unavailability of any support for low-level programming, possessing poor features in GUI 4, and having no control over garbage collection is putting Java developers in a dilemma on choosing an alternative to Java, such as JetBrains’ programming language, Kotlin, presently an officially supported language for Android development or Scala, an all-purpose programming language supporting functional programming and a strong static type system.

Today, we will discuss how developers can decide to choose Scala or Kotlin as an alternative to Java. We will briefly talk about Scala and Kotlin separately and talk about their application before moving forward to looking at the differences, advantages, and disadvantages of both and finally have you decide which one of these two suits your requirements.

User’s requirement

Before we begin, here is a question for the readers, ‘What are you looking for in the next programming language that you will use?’ It is an obvious question because the programming purposes drive the actual basis and need of developing a language. Do you need a language that strives to better Java or use a language that lets you do things that aren’t possible in Java? If it is the first reason, then Scala might be the best one for you, otherwise, it is a simplified programming language like Kotlin.

Now let us first briefly discuss Scala and Kotlin individually.

Scala

Developed by Martin Odersky, the first version of Scala was launched in the year 2003 and is a classic example of a  general-purpose, object-oriented computer language, offering a wide range of functional programming language features and a strong static type system. Inspired from Java itself, Scala, as the name suggests, is highly scalable and this very feature sets Scala apart from other programming languages.

When we say that Scala is inspired from Java, that means developers can code Scala in the same way they do for Java. Additionally, Scala makes it possible to use numerous Java and libraries within itself as well. It is designed to be able to use an elegant, concise and type-safe method to express common programming patterns. Scala is a very popular programming language amongst developers and rising up its ranks in the world of technology.

Although Scala comes with a number of plus points, there are some which make it a bit ineffective. Here are the strengths and weaknesses of Scala.

### Strengths:

• Full Support for Pattern Matching, Macros, and Higher-Kinded Types
• Has a very flexible code syntax
• Gets a bigger Community Support

### Weaknesses:

• Slow in compilation
• Challenging Binary Compilation
• Not so proficient in the Management of Null Safety

## Kotlin

Developed by JetBrains, Kotlin was released on February 2012 as an open-source language. Until now, there have been two released versions with the latest one being Kotlin 1.2, the most stable version that was released on November 28, 2017. Since Kotlin is extremely compatible with Java 6 the latest version of Java on Android, it has gained critical acclaim on Android worldwide and additionally, it offers various key features that are prepared only for Java 8 and not even Java 6 developers have access to that.

Kotlin provides seamless and flawless interoperability with Java. That means, developers can easily call Java codes from Kotlin and same goes the other way around. The built-in null safety feature avoids showing the NullPointerException (NPE) that makes developing android apps easy and joyful, something every android programmer wants.

Below mentioned are the key pointers on the strengths and weaknesses of Kotlin.

### Strengths

• Takes a Functional Programming Approach and Object-Oriented Programming style(OOP) Style
• Has Higher-Order Functions
• Short, Neat, and Verbose-Free Expression
• Supported by JetBrains and Google.

### Weaknesses:

• More limited Pattern Matching
• Shortage of Official Support
• Smaller Support Community.

## Ease of learning: Scala vs Kotlin

Scala is a powerful programming language packed with superior features and possesses a flexible syntax. It is not an easy language to learn and is a nightmare for newcomers. Kotlin, on the other hand, has been reported to have been an easy-to-learn language for many Java developers as getting started with Kotlin is relatively easy and so is writing codes. Even though it is a comparatively easier language to learn and code with, Kotlin lacks the solid set of features that is common in Scala. It might take less time to learn a programming language, but the most important thing to look for is a comprehensive array of features.

Scala, even though a very difficult language to learn, is cherished by the developers as it lets them do things that cannot be done in Kotlin

Here are the major differences between Scala and Kotlin:

ScalaKotlin
Type inferenceEfficient
ImmutabilityExtension Functions
Singleton objectMassive Interoperability
Concurrency controlLessens Crashes at Runtime
String interpolationSmart Cast Function
Higher-order functionSafe and Reliable
Case classes and Pattern matching Lazy computationLow adoption cost
Rich collection set

## Making the appropriate choice of language

Now, whether you may like a programming language or not, if that very language helps you get the best out of your job, then you will have to live with it. These are the facts about getting the best results. The outcome is the main factor in you deciding the appropriate language for your job. Kotlin is the only option for Android development as Android doesn’t use JVM, so any old JVM-compatible language will not work in Android. Kotlin has it all what it takes to compile, debug, and run the software on Android because of which it is in-built into Android Studio.

However, Kotlin is not so usable outside Android development. If you are one of the developers who like working with Eclipse for your IDE, then Scala IDE is better than the Kotlin Plugin even if you can make Eclipse work with both the languages with limitations. Scala IDE is more advanced than the Kotlin plugin and is easier to set up. Some developers found it quite difficult to make the Kotlin plugin work. This case is quite the same with NetBeans. Kotlin is still getting there but is already popular amongst Java developers as it offers an easier transition than Scala. Kotlin is still maturing, but many Java people find adopting it is an easier transition than Scala is.

Scala, however, is for developers who are focused more on discovering new ideas while Kotlin is for those who want to get results. Kotlin stresses fast compilation but is more restrictive while Scala gives a lot of flexibility. Go for Scala if you breathe functional programming! It has more appropriate features for this type of programming than Kotlin does. Scala supports currying and partial application, the methods of breaking down functions requiring multiple arguments offering more flexibility.

Go for the one that is the most appropriate one for your work, style of working and what you are aiming at. Think before you leap.

### The Outcome

At the end of the day, all that matters is what you want to use the language for. While Scala goes well for the projects that require a combination of functional, OOP style programming languages, and where programmers need to handle lots of data or complex modelling, Kotlin becomes the best choice when you want something less frustrating than Java while developing apps because using Kotlin makes app development less cumbersome and a great thing to work on. It is just like a better-looking version of Java with less lengthy codes.

### KnowledgeHut

Author

KnowledgeHut is an outcome-focused global ed-tech company. We help organizations and professionals unlock excellence through skills development. We offer training solutions under the people and process, data science, full-stack development, cybersecurity, future technologies and digital transformation verticals.
Website : https://www.knowledgehut.com

The Python Standard Library comprises of sophisticated and robust capabilities for working with larger packages. You will find modules for working with sockets and with files and file paths.Though there might be great packages that Python comes with, there are more exciting and fantastic projects outside the standard library which are mostly called the Python Packaging Index (PyPI). It is nothing but a repository of software for the Python programming language.The PyPI package is considered as an important property for Python being a powerful language. You can get access to thousands of libraries starting from Hello World to advanced deep learning libraries.What is PyPI"PyPI" should be pronounced like "pie pea eye", specifically with the "PI" pronounced as individual letters, but rather as a single sound. This minimizes confusion with the PyPy project, which is a popular alternative implementation of the Python language.The Python Package Index, abbreviated as PyPI is also known as the Cheese Shop. It is the official third-party software repository for Python, just like CPAN is the repository for  Perl.  Some package managers such as pip, use PyPI as the default source for packages and their dependencies. More than 113,000 Python packages can be accessed through PyPI.How to use PyPITo install the packages from PyPI you would need a package installer. The recommended package installer for PyPI is ‘pip’. Pip is installed along when you install Python on your system. To learn more about ‘pip’, you may go through our article on “What is pip”. The pip command is a tool for installing and managing Python packages, such as those found in the Python Package Index. It is a replacement for easy_install.To install a package from the Python Package Index, just open up your terminal and type in a search query using the PIP tool. The most common usage for pip is to install, upgrade or uninstall a package. Starting with a Small Python PackageWe will start with a small Python package that we will use as an example to publish to PyPI. You can get the full source code from the GitHub repository. The package is called reader and it is an application by which you can download and read articles. Below shows the directory structure of reader :reader/  │  ├── reader/  │   ├── config.txt  │   ├── feed.py  │   ├── __init__.py  │   ├── __main__.py  │   └── viewer.py  │  ├── tests/  │   ├── test_feed.py  │   └── test_viewer.py  │  ├── MANIFEST.in  ├── README.md  └── setup.py The source code of the package is in a reader subdirectory that is bound with a configuration file. The GitHub repository also contains few tests in a separate subdirectory. In the coming sections, we will discuss the working of the reader package and also take a look at the special files which include setup.py, README.md, MANIFEST.in, and others. Using the Article ReaderThe reader is a primitive data format used for providing users with the latest updated content. You can download the frequent articles from the article feed with the help of reader. You can get the list of articles using the reader:$python -m reader The latest tutorials from Real Python (https://realpython.com/) 0 How to Publish an Open-Source Python Package to PyPI 1 Python "while" Loops (Indefinite Iteration) 2 Writing Comments in Python (Guide) 3 Setting Up Python for Machine Learning on Windows 4 Python Community Interview With Michael Kennedy 5 Practical Text Classification With Python and Keras 6 Getting Started With Testing in Python 7 Python, Boto3, and AWS S3: Demystified 8 Python's range() Function (Guide) 9 Python Community Interview With Mike Grouchy 10 How to Round Numbers in Python 11 Building and Documenting Python REST APIs With Flask and Connexion – Part 2 12 Splitting, Concatenating, and Joining Strings in Python 13 Image Segmentation Using Color Spaces in OpenCV + Python 14 Python Community Interview With Mahdi Yusuf 15 Absolute vs Relative Imports in Python 16 Top 10 Must-Watch PyCon Talks 17 Logging in Python 18 The Best Python Books 19 Conditional Statements in PythonThe articles in the list are numbered. So if you want to read a particular article, you can just write the same command along with the number of the article you desire to read.For reading the article on “How to Publish an Open-Source Python Package to PyPI”, just add the serial number of the article:$ python -m reader 0  # How to Publish an Open-Source Python Package to PyPI  Python is famous for coming with batteries included. Sophisticated  capabilities are available in the standard library. You can find modules  for working with sockets, parsing CSV, JSON, and XML files, and  working with files and file paths. However great the packages included with Python are, there are many  fantastic projects available outside the standard library. These are  most often hosted at the Python Packaging Index (PyPI), historically  known as the Cheese Shop. At PyPI, you can find everything from Hello  World to advanced deep learning libraries.  ...  ...  ...You can read any of the articles in the list just by changing the article number with the command. Quick LookThe package comprises of five files which are the working hands of the reader. Let us understand the implementations one by one: config.txt -  It is a text configuration file that specifies the URL of the feed of articles. The configparser standard library is able to read the text file. This type of file contains key-value pairs that are distributed into different sections.  # config.txt [feed] url=https://realpython.com/atom.xml__main__.py - It is the entry point of your program whose duty is to control the main flow of the program. The double underscores denote the specialty of this file. Python executes the contents of the __main__.py file. # __main__.py from configparser import ConfigParser  from importlib import resources  import sys from reader import feed  from reader import viewer def main(): # Read URL of the Real Python feed from config file  configure=ConfigParser() configure.read_string(resources.readtext("reader","config.txt"))  URL=configure.get("feed","url") # If an article ID is given, show the article  if len(sys.argv) > 1:  article = feed.getarticle(URL, sys.argv[1])  viewer.show(article) # If no ID is given, show a list of all articles else: site = feed.getsite(URL)  titles = feed.gettitles(URL)  viewer.showlist(site,titles)  if __name__ == "__main__": main() __init__.py - It is also considered a special file because of the double underscore. It denotes the root of your package in which you can keep your package constants, your documentations and so on. # __init__.py # Version of the realpython-reader package  __version__= "1.0.0"__version__ is a special variable in Python used for adding numbers to your package which was introduced in PEP 396. The variables which are defined in __init__.py are available as variables in the namespace also. >>> import reader >>> reader.__version__ '1.0.0'feed.py - In the __main__.py, you can see two modules feed and viewer are imported which perform the actual work. The file feed.py  is used to read from a web feed and parse the result.  # feed.py import feedparser import html2text Cached_Feeds = dict() def _feed(url):  """Only read a feed once, by caching its contents""" if url not in _CACHED_FEEDS: Cached_Feeds[url]=feedparser.parse(url) return Cached_Feeds[url]viewer.py -  This file module contains two functions show() and show_list(). # viewer.py def show(article):  """Show one article""" print(article) def show_list(site,titles):  """Show list of articles""" print(f"The latest tutorials from {site}") for article_id,title in enumerate(titles): print(f"{article_id:>3}{title}")The function of show() is to print one article to the console. On the other hand, show_list prints a list of titles.Calling a Package You need to understand which file you should call to run the reader in cases where your package consists of four different source code files. The Python interpreter consists of an -m option that helps in specifying a module name instead of a file name.An example to execute two commands with a script hello.py:$python hello.py Hi there!$ python -m hello Hi there!The two commands above are equivalent. However, the latter one with -m has an advantage. You can also call Python built-in modules with the help of it: $python -m antigravity Created new window in existing browser session.The -m option also allows you to work with packages and modules:$ python -m reader ...The reader only refers to the directory. Python looks out for the file named __main__.py, if the file is found, it is executed otherwise an error message is printed: $python -m math python: No code object available for mathPreparing Your PackageSince now you have got your package, let us understand the necessary steps that are needed to be done before the uploading process. Naming the Package Finding a good and unique name for your package is the first and one of the most difficult tasks. PyPI has more than 150,000 packages already in their list, so chances are that your favorite name might be already taken. You need to perform some research work in order to find a perfect name. You can also use the PyPI search to verify whether it is already used or not. We will be using a more descriptive name and call it realpython-reader so that the reader package can be easily found on PyPI and then use it to install the package using pip:$ pip install realpython-readerHowever, the name we have given is realpython-reader but when we import it, it is still called as reader:>>> import reader >>> help(reader) >>> from reader import feed >>> feed.get_titles() ['How to Publish an Open-Source Python Package to PyPI', ...]You can use a variety of names for your package while importing on PyPI but it is suggested to use the same name or similar ones for better understanding. Configuring your PackageYour package should be included with some basic information which will be in the form of a setup.py file. The setup.py is the only fully supported way of providing information, though Python consists of initiatives that are used to simplify this collection of information.The setup.py file should be placed in the top folder of your package. An example of a setup.py  for reader: import pathlib from setuptools import setup # The directory containing this file HERE = pathlib.Path(__file__).parent # The text of the README file README = (HERE/"README.md").read_text() # This call to setup() does all the work setup( name="realpython-reader",  version="1.0.1",  descp="The latest Python tutorials",  long_descp=README, long_descp_content="text/markdown",  URL="https://github.com/realpython/reader",  author="Real Python",  authoremail="office@realpython.com",  license="MIT",  classifiers=[  "License :: OSI Approved :: MIT License",  "Programming Language :: Python :: 3",  "Programming Language :: Python :: 3.7",  ],  packages=["reader"],  includepackagedata=True,  installrequires=["feedparser","html2text"],  entrypoints={  "console_scripts":[  "realpython=reader.__main__:main",  ]  },  ) The necessary parameters available in setuptools in the call to setup() are as follows: name - The name of your package as being appeared on PyPI version - the present version of your package packages - the packages and subpackages which contain your source code You will also have to specify any subpackages if included. setuptools contains find_packages() whose job is to discover all your subpackages. You can also use it in the reader project:from setuptools import find_packages,setup  setup(  ... packages=find_packages(exclude=("tests",)), ... ) You can also add more information along with name, version, and packages which will make it easier to find on PyPI.Two more important parameters of  setup() : install_requires - It lists the dependencies your package has to the third-party libraries. feedparser and html2text are listed since they are the dependencies of reader.entry_points - It creates scripts to call a function within your package. Our script realpython calls the main() within the reader/__main__.py file.Documenting Your PackageDocumenting your package before releasing it is an important step. It can be a simple README file or a complete tutorial webpage like galleries or an API reference.  At least a README file with your project should be included at a minimum which should give a quick description of your package and also inform about the installation process and how to use it. In other words, you need to include your README as the long_descp argument to setup() which will eventually be displayed on PyPI. PyPI uses Markdown for package documentation. You can use the setup() parameter long_description_content_type to get the PyPI format you are working with. When you are working with bigger projects and want to add more documentation to your package, you can take the help of websites like GitHub and Read the Docs. Versioning Your Package Similarly like documentation, you need to add a version to your package. PyPI promises reproducibility by allowing a user to do one upload of a particular version for a package. If there are two systems with the same version of a package, it will behave in an exact manner. PEP 440 of Python provides a number of schemes for software versioning. However, for a simple project, let us stick to a simple versioning scheme. A simple versioning technique is semantic versioning which has three components namely MAJOR, MINOR, and PATCH and some simple rules about the incrementation process of each component: Increment the MAJOR version when you make incompatible API changes. Increment the MINOR version when you add functionality in a backward-compatible manner. Increment the PATCH version when you make backward-compatible bug fixes. (Source) You need to specify the different files inside your project. Also, if you want to verify whether the version numbers are consistent or not, you can do it using a tool called Bumpversion: $pip install bumpversionAdding Files To Your PackageYour package might include other files other than source code files like data files, binaries, documentation and configuration files. In order to add such files, we will use a manifest file. In most cases, setup() creates a manifest that includes all code files as well as README files. However, if you want to change the manifest, you can create a manifest template of your own. The file should be called MANIFEST.in and it will specify rules for what needs to be included and what needs to be excluded: include reader/*.txtThis will add all the .txt files in the reader directory. Other than creating the manifest, the non-code files also need to be copied. This can be done by setting the include_package_data toTrue: setup( ... include_package_data=True, ... )Publishing to PyPI For publishing your package to the real world, you need to first start with registering yourself on PyPI and also on TestPyPI, which is useful because you can give a trial of the publishing process without any further consequences. You will have to use a tool called Twine to upload your package ton PyPI:$ pip install twineBuilding Your PackageThe packages on PyPI are wrapped into distribution packages, out of which the most common are source archives and Python wheels. A source archive comprises of your source code and other corresponding support files wrapped into one tar file. On the other hand, a Python wheel is a zip archive that also contains your code. However, the wheel can work with any extensions, unlike source archives. Run the following command in order to create a source archive and a wheel for your package: $python setup.py sdist bdist_wheelThe command above will create two files in a newly created directory called dist, a source archive and a wheel: reader/ │ └── dist/ ├── realpython_reader-1.0.0-py3-none-any.whl └── realpython-reader-1.0.0.tar.gz The command-line arguments like the sdist and bdist_wheel arguments are all implemented int the upstream distutils standard library. Using the --help-commands option, you list all the available arguments:$ python setup.py --help-commands  Standard commands:    build             build everything needed to install    build_py          "build" pure Python modules (copy to build directory)    < ... many more commands ...>Testing Your Package In order to test your package, you need to check whether the distribution packages you have newly created contain the expected files. You also need to list the contents of the tar source archive on Linux and macOS platforms: $tar tzf realpython-reader-1.0.0.tar.gz realpython-reader-1.0.0/ realpython-reader-1.0.0/setup.cfg realpython-reader-1.0.0/README.md realpython-reader-1.0.0/reader/ realpython-reader-1.0.0/reader/feed.py realpython-reader-1.0.0/reader/__init__.py realpython-reader-1.0.0/reader/viewer.py realpython-reader-1.0.0/reader/__main__.py realpython-reader-1.0.0/reader/config.txt realpython-reader-1.0.0/PKG-INFO realpython-reader-1.0.0/setup.py realpython-reader-1.0.0/MANIFEST.in realpython-reader-1.0.0/realpython_reader.egg-info/ realpython-reader-1.0.0/realpython_reader.egg-info/SOURCES.txt realpython-reader-1.0.0/realpython_reader.egg-info/requires.txt realpython-reader-1.0.0/realpython_reader.egg-info/dependency_links.txt realpython-reader-1.0.0/realpython_reader.egg-info/PKG-INFO realpython-reader-1.0.0/realpython_reader.egg-info/entry_points.txt realpython-reader-1.0.0/realpython_reader.egg-info/top_level.txt On Windows, you can make use of the utility tool 7-zip to look inside the corresponding zip file. You should make sure that all the subpackages and supporting files are included in your package along with all the source code files as well as the newly built files. You can also run twine check on the files created in dist to check if your package description will render properly on PyPI:$ twine check dist/* Checking distribution dist/realpython_reader-1.0.0-py3-none-any.whl: Passed  Checking distribution dist/realpython-reader-1.0.0.tar.gz: Passed Uploading Your PackageNow you have reached the final step,i.e. Uploading your package to PyPI. Make sure you upload your package first to TestPyPI to check whether it is working according to your expectation and then use the Twine tool and instruct it to upload your newly created distribution: $twine upload --repository-url https://test.pypi.org/legacy/ dist/* After the uploading process is over, you can again go to TestPyPI and look at your project being displayed among the new releases. However, if you have your own package to publish, the command is short:$ twine upload dist/* Give your username and password and it’s done. Your package has been published on PyPI. To look up your package, you can either search it or look at the Your projects page or you can just directly go to the URL of your project: pypi.org/project/your-package-name/. After completing the publishing process, you can download it in your system using pip: $pip install your-package-nameMiscellaneous Tools There are some useful tools that are good to know when creating and publishing Python packages. Some of these are mentioned below. Virtual Environments Each virtual environment has its own Python binary and can also have its own set of installed Python packages in its directories. These packages are independent in nature. Virtual environments are useful in situations where there are a variety of requirements and dependencies while working with different projects. You can grab more information about virtual environments in the following references: Python Virtual Environments Pipenv It is recommended to check your package inside a basic virtual environment so that to make sure all necessary dependencies in your setup.py file are included. Cookiecutter Cookiecutter sets up your project by asking a few questions based on a template. Python contains many different templates. Install Cookiecutter using pip:$ pip install cookiecutterTo understand cookiecutter, we will use a template called pypackage-minimal. If you want to use a template, provide the link of the template to the cookiecutter: cookiecutter https://github.com/kragniz/cookiecutter-pypackage-minimal author_name [Louis Taylor]: Real Python author_email [louis@kragniz.eu]: office@realpython.com package_name [cookiecutter_pypackage_minimal]: realpython-reader package_version [0.1.0]: package_description [...]: Read Real Python tutorials package_url [...]: https://github.com/realpython/reader readme_pypi_badge [True]: readme_travis_badge [True]: False readme_travis_url [...]: Cookiecutter sets up your project after you have set up answered a series of questions. The template above will create the following files and directories: realpython-reader/ │ ├── realpython-reader/ │ └── __init__.py │ ├── tests/ │ ├── __init__.py │ └── test_sample.py │ ├── README.rst ├── setup.py └── tox.ini You can also take a look at the documentation of cookiecutter for all the available cookiecutters and how to create your own template. Summary Let us sum up the necessary steps we have learned in this article so far to publish your own package - Finding a good and unique name for your packageConfiguring your package using setup.py Building your package Publishing your package to PyPI Moreover, you have also learned to use a few new tools that help in simplifying the process of publishing packages. You can reach out to Python’s Packaging Authority for more detailed and comprehensive information. To gain more knowledge about Python tips and tricks, check our Python tutorial and get a good hold over coding in Python by joining the Python certification course. Rated 4.5/5 based on 34 customer reviews 12086 What is PyPI & How To Publish An Open-Source P... The Python Standard Library comprises of sophistic... Read More ## How to Round Numbers in Python While you are dealing with data, sometimes you may come across a biased dataset. In statistics, bias is whereby the expected value of the results differs from the true underlying quantitative parameter being estimated. Working with such data can be dangerous and can lead you to incorrect conclusions. To learn more about various other concepts of Python, go through our Python Tutorials or enroll to our Python Certification course online.There are many types of biases such as selection bias, reporting bias, sampling bias and so on. Similarly, rounding bias is related to numeric data. In this article we will see:Why is it important to know the ways to round numbersHow to use various strategies to round numbersHow data is affected by rounding itHow to use NumPy arrays and Pandas DataFrames to round numbersLet us first learn about Python’s built-in rounding process.About Python’s Built-in round() FunctionPython Programming offers a built-in round() function which rounds off a number to the given number of digits and makes rounding of numbers easier. The function round() accepts two numeric arguments, n and n digits and then returns the number n after rounding it to ndigits. If the number of digits are not provided for round off, the function rounds off the number n to the nearest integer.Suppose, you want to round off a number, say 4.5. It will be rounded to the nearest whole number which is 5. However, the number 4.74 will be rounded to one decimal place to give 4.7.It is important to quickly and readily round numbers while you are working with floats which have many decimal places. The inbuilt Python function round() makes it simple and easy.Syntaxround(number, number of digits)The parameters in the round() function are:number - number to be roundednumber of digits (Optional) - number of digits up to which the given number is to be rounded.The second parameter is optional. In case, if it is missing then round() function returns:For an integer, 12, it rounds off to 12For a decimal number, if the last digit after the decimal point is >=5 it will round off to the next whole number, and if =5 print(round(5.476, 2)) # when the (ndigit+1)th digit is 1 print(round("x", 2)) TypeError: type str doesn't define __round__ methodAnother example,print(round(1.5)) print(round(2)) print(round(2.5))The output will be:2 2 2The function round() rounds 1.5 up to 2, and 2.5 down to 2. This is not a bug, the round() function behaves this way. In this article you will learn a few other ways to round a number. Let us look at the variety of methods to round a number.Diverse Methods for RoundingThere are many ways to round a number with its own advantages and disadvantages. Here we will learn some of the techniques to rounding a number.TruncationTruncation, as the name means to shorten things. It is one of the simplest methods to round a number which involves truncating a number to a given number of digits. In this method, each digit after a given position is replaced with 0. Let us look into some examples.ValueTruncated ToResult19.345Tens place1019.345Ones place1919.345Tenths place19.319.345Hundredths place19.34The truncate() function can be used for positive as well as negative numbers:>>> truncate(19.5) 19.0 >>> truncate(-2.852, 1) -2.8 >>> truncate(2.825, 2) 2.82The truncate() function can also be used to truncate digits towards the left of the decimal point by passing a negative number.>>> truncate(235.7, -1) 230.0 >>> truncate(-1936.37, -3) -1000.0When a positive number is truncated, we are basically rounding it down. Similarly, when we truncate a negative number, the number is rounded up. Let us look at the various rounding methods.Rounding UpThere is another strategy called “rounding up” where a number is rounded up to a specified number of digits. For example:ValueRound Up ToResult12.345Tens place2018.345Ones place1918.345Tenths place18.418.345Hundredths place18.35The term ceiling is used in mathematics to explain the nearest integer which is greater than or equal to a particular given number. In Python, for “rounding up” we use two functions namely,ceil() function, andmath() functionA non-integer number lies between two consecutive integers. For example, considering a number 5.2, this will lie between 4 and 5. Here, ceiling is the higher endpoint of the interval, whereas floor is the lower one. Therefore, ceiling of 5.2 is 5, and floor of 5.2 is 4. However, the ceiling of 5 is 5.In Python, the function to implement the ceiling function is the math.ceil() function. It always returns the closest integer which is greater than or equal to its input.>>> import math >>> math.ceil(5.2) 6 >>> math.ceil(5) 5 >>> math.ceil(-0.5) 0If you notice you will see that the ceiling of -0.5 is 0, and not -1.Let us look into a short code to implement the “rounding up” strategy using round_up() function:def round_up(n, decimals=0): multiplier = 10 ** decimals return math.ceil(n * multiplier) / multiplierLet’s look at how round_up() function works with various inputs:>>> round_up(3.1) 4.0 >>> round_up(3.23, 1) 3.3 >>> round_up(3.543, 2) 3.55You can pass negative values to decimals, just like we did in truncation.>>> round_up(32.45, -1) 40.0 >>> round_up(3352, -2) 3400You can follow the diagram below to understand round up and round down. Round up to the right and down to the left.Rounding up always rounds a number to the right on the number line, and rounding down always rounds a number to the left on the number line.Rounding DownSimilar to rounding up we have another strategy called rounding down whereValueRounded Down ToResult19.345Tens place1019.345Ones place1919.345Tenths place19.319.345Hundredths place19.34In Python, rounding down can be implemented using a similar algorithm as we truncate or round up. Firstly you will have to shift the decimal point and then round an integer. Lastly shift the decimal point back.math.ceil() is used to round up to the ceiling of the number once the decimal point is shifted. For “rounding down” we first need to round the floor of the number once the decimal point is shifted.>>> math.floor(1.2) 1 >>> math.floor(-0.5) -1Here’s the definition of round_down():def round_down(n, decimals=0): multiplier = 10 ** decimals return math.floor(n * multiplier) / multiplierThis is quite similar to round_up() function. Here we are using math.floor() instead of math.ceil().>>> round_down(1.5) 1 >>> round_down(1.48, 1) 1.4 >>> round_down(-0.5) -1Rounding a number up or down has extreme effects in a large dataset. After rounding up or down, you can actually remove a lot of precision as well as alter computations.Rounding Half UpThe “rounding half up” strategy rounds every number to the nearest number with the specified precision, and breaks ties by rounding up. Here are some examples:ValueRound Half Up ToResult19.825Tens place1019.825Ones place2019.825Tenths place19.819.825Hundredths place19.83In Python, rounding half up strategy can be implemented by shifting the decimal point to the right by the desired number of places. In this case you will have to determine whether the digit after the shifted decimal point is less than or greater than equal to 5.You can add 0.5 to the value which is shifted and then round it down with the math.floor() function.def round_half_up(n, decimals=0): multiplier = 10 ** decimals return math.floor(n*multiplier + 0.5) / multiplierIf you notice you might see that round_half_up() looks similar to round_down. The only difference is to add 0.5 after shifting the decimal point so that the result of rounding down matches with the expected value.>>> round_half_up(19.23, 1) 19.2 >>> round_half_up(19.28, 1) 19.3 >>> round_half_up(19.25, 1) 19.3Rounding Half DownIn this method of rounding, it rounds to the nearest number similarly like “rounding half up” method, the difference is that it breaks ties by rounding to the lesser of the two numbers. Here are some examples:ValueRound Half Down ToResult16.825Tens place1716.825Ones place1716.825Tenths place16.816.825Hundredths place16.82In Python, “rounding half down” strategy can be implemented by replacing math.floor() in the round_half_up() function with math.ceil() and then by subtracting 0.5 instead of adding:def round_half_down(n, decimals=0): multiplier = 10 ** decimals return math.ceil(n*multiplier - 0.5) / multiplierLet us look into some test cases.>>> round_half_down(1.5) 1.0 >>> round_half_down(-1.5) -2.0 >>> round_half_down(2.25, 1) 2.2In general there are no bias for both round_half_up() and round_half_down(). However, rounding of data with more number of ties results in bias. Let us consider an example to understand better.>>> data = [-2.15, 1.45, 4.35, -12.75]Let us compute the mean of these numbers:>>> statistics.mean(data) -2.275Now let us compute the mean on the data after rounding to one decimal place with round_half_up() and round_half_down():>>> rhu_data = [round_half_up(n, 1) for n in data] >>> statistics.mean(rhu_data) -2.2249999999999996 >>> rhd_data = [round_half_down(n, 1) for n in data] >>> statistics.mean(rhd_data) -2.325The round_half_up() function results in a round towards positive infinity bias, and round_half_down() results in a round towards negative infinity bias.Rounding Half Away From ZeroIf you have noticed carefully while going through round_half_up() and round_half_down(), neither of the two is symmetric around zero:>>> round_half_up(1.5) 2.0 >>> round_half_up(-1.5) -1.0 >>> round_half_down(1.5) 1.0 >>> round_half_down(-1.5) -2.0In order to introduce symmetry, you can always round a tie away from zero. The table mentioned below illustrates it clearly:ValueRound Half Away From Zero ToResult16.25Tens place2016.25Ones place1616.25Tenths place16.3-16.25Tens place-20-16.25Ones place-16-16.25Tenths place-16.3The implementation of “rounding half away from zero” strategy on a number n is very simple. All you need to do is start as usual by shifting the decimal point to the right a given number of places and then notice the digit d immediately to the right of the decimal place in this new number. Here, there are four cases to consider:If n is positive and d >= 5, round upIf n is positive and d < 5, round downIf n is negative and d >= 5, round downIf n is negative and d < 5, round upAfter rounding as per the rules mentioned above, you can shift the decimal place back to the left.There is a question which might come to your mind - How do you handle situations where the number of positive and negative ties are drastically different? The answer to this question brings us full circle to the function that deceived us at the beginning of this article: Python’s built-in round() function.Rounding Half To EvenThere is a way to mitigate rounding bias while you are rounding values in a dataset. You can simply round ties to the nearest even number at the desired precision. Let us look at some examples:ValueRound Half To Even ToResult16.255Tens place2016.255Ones place1616.255Tenths place16.216.255Hundredths place16.26To prove that round() really does round to even, let us try on a few different values:>>> round(4.5) 4 >>> round(3.5) 4 >>> round(1.75, 1) 1.8 >>> round(1.65, 1) 1.6The Decimal ClassThe decimal module in Python is one of those features of the language which you might not be aware of if you have just started learning Python. Decimal “is based on a floating-point model which was designed with people in mind, and necessarily has a paramount guiding principle – computers must provide an arithmetic that works in the same way as the arithmetic that people learn at school.” – except from the decimal arithmetic specification. Some of the benefits of the decimal module are mentioned below -Exact decimal representation: 0.1 is actually 0.1, and 0.1 + 0.1 + 0.1 - 0.3 returns 0, as expected.Preservation of significant digits: When you add 1.50 and 2.30, the result is 3.80 with the trailing zero maintained to indicate significance.User-alterable precision: The default precision of the decimal module is twenty-eight digits, but this value can be altered by the user to match the problem at hand.Let us see how rounding works in the decimal module.>>> import decimal >>> decimal.getcontext() Context( prec=28, rounding=ROUND_HALF_EVEN, Emin=-999999, Emax=999999, capitals=1, clamp=0, flags=[], traps=[ InvalidOperation, DivisionByZero, Overflow ] )The function decimal.getcontext() returns a context object which represents the default context of the decimal module. It also includes the default precision and the default rounding strategy.In the above example, you will see that the default rounding strategy for the decimal module is ROUND_HALF_EVEN. It allows to align with the built-in round() functionLet us create a new Decimal instance by passing a string containing the desired value and declare a number using the decimal module’s Decimal class.>>> from decimal import Decimal >>> Decimal("0.1") Decimal('0.1')You may create a Decimal instance from a floating-point number but in that case, a floating-point representation error will be introduced. For example, this is what happens when you create a Decimal instance from the floating-point number 0.1>>> Decimal(0.1) Decimal('0.1000000000000000055511151231257827021181583404541015625')You may create Decimal instances from strings containing the decimal numbers you need in order to maintain exact precision.Rounding a Decimal using the .quantize() method:>>> Decimal("1.85").quantize(Decimal("1.0")) Decimal('1.8')The Decimal("1.0") argument in .quantize() allows to determine the number of decimal places in order to round the number. As 1.0 has one decimal place, the number 1.85 rounds to a single decimal place. Rounding half to even is the default strategy, hence the result is 1.8.Decimal class:>>> Decimal("2.775").quantize(Decimal("1.00")) Decimal('2.78')Decimal module provides another benefit. After performing arithmetic the rounding is taken care of automatically and also the significant digits are preserved.>>> decimal.getcontext().prec = 2 >>> Decimal("2.23") + Decimal("1.12") Decimal('3.4')To change the default rounding strategy, you can set the decimal.getcontect().rounding property to any one of several flags. The following table summarizes these flags and which rounding strategy they implement:FlagRounding Strategydecimal.ROUND_CEILINGRounding updecimal.ROUND_FLOORRounding downdecimal.ROUND_DOWNTruncationdecimal.ROUND_UPRounding away from zerodecimal.ROUND_HALF_UPRounding half away from zerodecimal.ROUND_HALF_DOWNRounding half towards zerodecimal.ROUND_HALF_EVENRounding half to evendecimal.ROUND_05UPRounding up and rounding towards zeroRounding NumPy ArraysIn Data Science and scientific computation, most of the times we store data as a NumPy array. One of the most powerful features of NumPy is the use of vectorization and broadcasting to apply operations to an entire array at once instead of one element at a time.Let’s generate some data by creating a 3×4 NumPy array of pseudo-random numbers:>>> import numpy as np >>> np.random.seed(444) >>> data = np.random.randn(3, 4) >>> data array([[ 0.35743992, 0.3775384 , 1.38233789, 1.17554883], [-0.9392757 , -1.14315015, -0.54243951, -0.54870808], [ 0.20851975, 0.21268956, 1.26802054, -0.80730293]])Here, first we seed the np.random module to reproduce the output easily. Then a 3×4 NumPy array of floating-point numbers is created with np.random.randn().Do not forget to install pip3 before executing the code mentioned above. If you are using Anaconda you are good to go.To round all of the values in the data array, pass data as the argument to the np.around() function. The desired number of decimal places is set with the decimals keyword argument. In this case, round half to even strategy is used similar to Python’s built-in round() function.To round the data in your array to integers, NumPy offers several options which are mentioned below:numpy.ceil()numpy.floor()numpy.trunc()numpy.rint()The np.ceil() function rounds every value in the array to the nearest integer greater than or equal to the original value:>>> np.ceil(data) array([[ 1., 1., 2., 2.], [-0., -1., -0., -0.], [ 1., 1., 2., -0.]])Look at the code carefully, we have a new number! Negative zero! Let us now take a look at Pandas library, widely used in Data Science with Python.Rounding Pandas Series and DataFramePandas has been a game-changer for data analytics and data science. The two main data structures in Pandas are Dataframe and Series. Dataframe works like an Excel spreadsheet whereas you can consider Series to be columns in a spreadsheet. Series.round() and DataFrame.round() methods. Let us look at an example.Do not forget to install pip3 before executing the code mentioned above. If you are using Anaconda you are good to go.>>> import pandas as pd >>> # Re-seed np.random if you closed your REPL since the last example >>> np.random.seed(444) >>> series = pd.Series(np.random.randn(4)) >>> series 0 0.357440 1 0.377538 2 1.382338 3 1.175549 dtype: float64 >>> series.round(2) 0 0.36 1 0.38 2 1.38 3 1.18 dtype: float64 >>> df = pd.DataFrame(np.random.randn(3, 3), columns=["A", "B", "C"]) >>> df A B C 0 -0.939276 -1.143150 -0.542440 1 -0.548708 0.208520 0.212690 2 1.268021 -0.807303 -3.303072 >>> df.round(3) A B C 0 -0.939 -1.143 -0.542 1 -0.549 0.209 0.213 2 1.268 -0.807 -3.303 The DataFrame.round() method can also accept a dictionary or a Series, to specify a different precision for each column. For instance, the following examples show how to round the first column of df to one decimal place, the second to two, and the third to three decimal places: >>> # Specify column-by-column precision with a dictionary >>> df.round({"A": 1, "B": 2, "C": 3}) A B C 0 -0.9 -1.14 -0.542 1 -0.5 0.21 0.213 2 1.3 -0.81 -3.303 >>> # Specify column-by-column precision with a Series >>> decimals = pd.Series([1, 2, 3], index=["A", "B", "C"]) >>> df.round(decimals) A B C 0 -0.9 -1.14 -0.542 1 -0.5 0.21 0.213 2 1.3 -0.81 -3.303 If you need more rounding flexibility, you can apply NumPy's floor(), ceil(), and print() functions to Pandas Series and DataFrame objects: >>> np.floor(df) A B C 0 -1.0 -2.0 -1.0 1 -1.0 0.0 0.0 2 1.0 -1.0 -4.0 >>> np.ceil(df) A B C 0 -0.0 -1.0 -0.0 1 -0.0 1.0 1.0 2 2.0 -0.0 -3.0 >>> np.rint(df) A B C 0 -1.0 -1.0 -1.0 1 -1.0 0.0 0.0 2 1.0 -1.0 -3.0 The modified round_half_up() function from the previous section will also work here: >>> round_half_up(df, decimals=2) A B C 0 -0.94 -1.14 -0.54 1 -0.55 0.21 0.21 2 1.27 -0.81 -3.30Best Practices and ApplicationsNow that you have come across most of the rounding techniques, let us learn some of the best practices to make sure we round numbers in the correct way.Generate More Data and Round LaterSuppose you are dealing with a large set of data, storage can be a problem at times. For example, in an industrial oven you would want to measure the temperature every ten seconds accurate to eight decimal places, using a temperature sensor. These readings will help to avoid large fluctuations which may lead to failure of any heating element or components. We can write a Python script to compare the readings and check for large fluctuations.There will be a large number of readings as they are being recorded each and everyday. You may consider to maintain three decimal places of precision. But again, removing too much precision may result in a change in the calculation. However, if you have enough space, you can easily store the entire data at full precision. With less storage, it is always better to store at least two or three decimal places of precision which are required for calculation.In the end, once you are done computing the daily average of the temperature, you may calculate it to the maximum precision available and finally round the result.Currency Exchange and RegulationsWhenever we purchase an item from a particular place, the tax amount paid against the amount of the item depends largely on geographical factors. An item which costs you2 may cost you less (say \$1.8)  if you buy the same item from a different state. It is due to regulations set forth by the local government.In another case, when the minimum unit of currency at the accounting level in a country is smaller than the lowest unit of physical currency, Swedish rounding is done. You can find a list of such rounding methods used by various countries if you look up on the internet.If you want to design any such software for calculating currencies, keep in mind to check the local laws and regulations applicable in your present location.Reduce errorAs you are rounding numbers in a large datasets used in complex computations, your primary concern should be to limit the growth of the error due to rounding.SummaryIn this article we have seen a few methods to round numbers, out of those “rounding half to even” strategy minimizes rounding bias the best. We are lucky to have Python, NumPy, and Pandas already have built-in rounding functions to use this strategy. Here, we have learned about -Several rounding strategies, and how to implement in pure Python.Every rounding strategy inherently introduces a rounding bias, and the “rounding half to even” strategy mitigates this bias well, most of the time.You can round NumPy arrays and Pandas Series and DataFrame objects.If you enjoyed reading this article and found it to be interesting, leave a comment. To learn more about rounding numbers and other features of Python, join our Python certification course.
Rated 5.0/5 based on 43 customer reviews
13137
How to Round Numbers in Python

While you are dealing with data, sometimes you may... Read More