1

I am very upset about the way to convert a float into integer requiring rounding.

$ python3
>>> 18.31
18.31
>>> int(18.31 * 100)
1830
>>> 18.31 * 100
1830.9999999999998
>>> round(18.31 * 100)
1831

Of course working with float require more clock cycles, is round the best performing way to do such a simple operation?

Tiago Pimenta
  • 736
  • 7
  • 20
  • Why would you be more worried about calling `round` than calling `int`? – user2357112 Oct 13 '18 at 02:02
  • Please define "best". What are your criterion for judging between alternatives? – John Coleman Oct 13 '18 at 02:03
  • @user2357112 I believe it should use more cpu to calculate. – Tiago Pimenta Oct 13 '18 at 02:04
  • What are you expecting? – Reblochon Masque Oct 13 '18 at 02:09
  • @JohnColeman for me it sounds like a buggy behaviour, why simple int conversion is losing so much precision, if I do 18.31 * 100 / 100 I have the same number back, so just int(18.31 * 100) should work, there is no other way other than rounding? – Tiago Pimenta Oct 13 '18 at 02:09
  • @ReblochonMasque I was expecting int(18.31 * 100) to give 1831, that is it, why not? – Tiago Pimenta Oct 13 '18 at 02:11
  • This seems like another duplicate of [is floating point math broken?](https://stackoverflow.com/q/588004/4996248) – John Coleman Oct 13 '18 at 02:12
  • I was just about to link that, @JohnColeman ;) But I'm not sure if it's an exact dupe. – PM 2Ring Oct 13 '18 at 02:14
  • @PM2Ring It is seldom an exact duplicate, just a common motif that pops up at least once a week. – John Coleman Oct 13 '18 at 02:15
  • Floats aren't decimal numbers, they're binary. Like many other languages, Python uses IEEE-754 binary64 for the `float` type (C calls that `double`). That gives you 53 significant bits, but it can only represent binary fractions with a denominator <= `2**53` exactly. – PM 2Ring Oct 13 '18 at 02:19
  • @JohnColeman Fair enough, and it does contain all the necessary info, or links to it. Tiago, if after studying the linked question you feel you need a more specific answer please let me know. – PM 2Ring Oct 13 '18 at 02:22
  • 1
    If you want 18.31 to be exactly 18.31 because eg it's a money value you shouldn't be using floats. Use the Decimal type from the decimal module, and initialize your values using strings. Otherwise, don't worry about it, and use the appropriate `format` options when you want to display floats values nicely. – PM 2Ring Oct 13 '18 at 02:28

0 Answers0