 # How can I round a decimal?

how to decide the number of digits after the dot (this is a general question. I have seen many funny 143.0000000001) thks

1 Like
``````n = 5/3
print("As a float, n = {:.3f}".format(n))

# Output:
As a float, n = 1.667
``````
2 Likes

That is the result of floating point arithmetic, the rather complex process by which computers do math in binary. The error is very, very tiny, something on the order of 10 to the minus 14. We can expect this sort of result when multiplying floats, or when dividing, either float or integer.

If 143.0000000001 is the result of division, and you always want an integer quotient, use floor division

``````x // y => int quotient (i.e., 143)
``````

If you want a float, but with a single decimal place,

``````round(143.0000000001, 0) => 143.0
``````

or,

``````round(143.0000000001, 1) => 143.0
``````

We can floor divide by `1` to convert to an int

`````` 143.0000000001 // 1 => 143
``````

All of the above preserve the number type.

We can convert an int to a float (in Python 3) by dividing by 1.

``143 / 1 => 143.0``
1 Like

“Integer division” using the // operator with a float in either position results in a float.

``````>>> 143.01//1
143.0
>>> 143//1.0
143.0
>>>
``````

… but the math.floor() function returns an int:

``````>>> import math
>>> math.floor(143.01)
143
>>>
``````
1 Like

D’oh! I know that. What was I thinking? Blame correction bias, or blindness to facts known. With aging, one suspects this will continue to creep in. Thanks for setting us right. (Aside: Made you look! )

What is reinforced is the fact that `int` is not a given. The quotient can be a float with a singular decimal place, of value, zero, and still be an equivalent quantity to an int of same whole number value.

This is likely not the first time committing this same blunder. Some of us have a hard time storing a permanent correctness on binary choices. Taken over time, asked the same question we will give a spread of responses, not always the definitive.

Being correct is not as important as being corrected, which for cases such as above described, it’s the correct prescription. A need for others to catch those slips is greater than ever in a binary learning environment. Mistakes help us learn, especially if they help us hook on to the definitive with an everlasting certainty.

1 Like

… the fact that `int` is not a given … This is likely not the first time committing this same blunder.

Ah! So true, and so frustrating to discover when you have come up with an especially imaginative way to get at a certain index, that it turns out to be a float!

1 Like

merci pour votre réponse

1 Like

To avoid floating point division and rounding inaccuracies use math or numpy module. As I am aware they solve the issue