7

I am trying to round a floating point number in python to zero decimal places.

However, the round method is leaving a trailing 0 every time.

value = 10.01
rounded_value = round(value)
print rounded_value

results in 10.0 but I want 10

How can this be achieved? Converting to an int?

Marty Wallace
  • 34,046
  • 53
  • 137
  • 200

4 Answers4

18

Pass the rounded value to int() to get rid of decimal digits:

>>> value = 10.01
>>> int(round(value))
10
>>> value = 10.55
>>> int(round(value))
11
Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504
3

Casting to an int would certainly be the easiest way. If you are hell-bent on keeping it a float here's how to do it courtesy of Alex Martelli:

print ('%f' % value).rstrip('0').rstrip('.')
Lennart Regebro
  • 167,292
  • 41
  • 224
  • 251
Imre Kerr
  • 2,388
  • 14
  • 34
3

10.0 and 10 are the same float value. When you print that value, you get the string 10.0, because that's the default string representation of the value. (The same string you get by calling str(10.0).)

If you want a non-default representation, you need to ask for it explicitly. For example, using the format function:

print format(rounded_value, '.0f')

Or, using the other formatting methods:

print '{:.0f}'.format(rounded_value)
print '%.0f' % (rounded_value,)

The full details for why you want '.0f' are described in the Format Specification Mini-Language, but intuitively: the f means you want fixed-point format (like 10.0 instead of, say, 1.0E2), and the .0 means you want no digits after the decimal point (like 10 instead of 10.0).

Meanwhile, if the only reason you rounded the value was for formatting… never do that. Leave the precision on the float, then trim it down in the formatting:

print format(value, '.0f')
abarnert
  • 354,177
  • 51
  • 601
  • 671
  • it is worth pointing out that `round()` and `".0f"` can produce different results e.g., for `-0.5` (different rounding rules). – jfs May 27 '13 at 00:30
  • @J.F.Sebastian: Yes, I tried to clarify that in the last paragraph, but I don't think it was very clear. Call `round` to round a float to another float; `format` to format a float as a string. Using either one when you mean the other is equally wrong. And sometimes, you will want to do both (as in my initial example, where I called `format` on the `rounded_value`). – abarnert May 28 '13 at 08:12
  • Is it possible to have a dynamic value in the rounding amount? e.g. `{0:.{1}f}.format(value, decimals_count)` – Tjorriemorrie Feb 13 '15 at 10:30
1

You'll find a function number_shaver() that cuts trailing zeros of numbers in the EDIT 2 of this post.

Another post in the same thread explains how the regex in number_shaver() works.

I improved the regex in another thread some days later.

Community
  • 1
  • 1
eyquem
  • 26,771
  • 7
  • 38
  • 46