Fixed number of decimal places in Python
📁 python, ии
Is there an analog of the toFixed() function in JS in Python? I need something like this:
>>> a = 12.3456789>>> a.toFixed(2)'12.35'>>> a.toFixed(0)'12'>>> b = 12.000001>>> b.toFixed(3)'12.000' The most idiomatic and ideologically correct way:
result = [int(item) for item in a]For fans of functional style:
result = list(map(int, a))Here the map function applies the int function to each element of the object a, then the result is converted to a list.
This option is considered less "Pythonic", but it also has a right to exist (at the very least, in many cases the map notation is more compact than the list comprehension option).
Log in to leave an answer
Интересные статьи
@Override Error in Eclipse: How to Defeat "Must Override a Superclass Method"
Serverless Functions in Java: AWS Lambda from A to Z
Code That Survives Hell: C++ for Radioactive Environments
instanceof in Java: Is a null check necessary? Under the hood analysis