Billy Mays wrote: > On 7/21/2011 10:40 PM, Thomas 'PointedEars' Lahn wrote: >> Billy Mays wrote: >>> On 07/21/2011 08:46 AM, Web Dreamer wrote: >>>> If you do not want to use 'float()' try: >>>> >>>> int(x.split('.')[0]) >>> >>> This is right. >> >> Assuming that the value of `x' is in the proper format, of course. Else >> you might easily cut to the first one to three digits of a string >> representation (if `.' is the thousands separator of the locale, e. g.) > > The point (which was clear to me) was to convert a properly formatted > string representation of a floating point number to an integer. We > might also assume the number could be a hex encoded float or be in > scientific notation. If the input is not properly formatted, it is > unreasonable for us to return a correct value.
By "*proper* format" I was not referring to the user input. It is not up to you to define which number formats in the rest of the world can be considered proper. Indeed, Switzerland uses 1'234.56, and I find that quite reasonable, even though I am German and in Germany 1.234,56 is used (which I was referring to). >>>> But, the problem is the same as with int(float(x)), the integer number >>>> is still not as close as possible as the original float value. >>>> >>>> I would in fact consider doing this: >>>> >>>> int(round(float(x))) >>> >>> This is wrong, since there is a loss of information in the float cast: >>> >>> >>> float('9007199254740993.0') >>> 9007199254740992.0 >>> >>> Notice the last digit switched from a 3 to a 2? Floats in python don't >>> have arbitrary accuracy. You would need to import decimal and use it >>> for rounding to work properly. >> >> It should be floor() though, for that is what int() does. > > Um, what? _____ >>> print math.floor.__doc__ floor(x) Return the floor of x as a float. This is the largest integral value <= x. _____ The point I was trying to make was that round() would return a different result than intended by the OP when the fractional part was greater than or equal to 0.5. So it should not be used here. Instead, from math import floor int(floor(float(x))) should be used. (I assumed before, without testing, that Python had a global floor() function. Sorry.) There is still the rounding error as there is no arbitrary precision with built-in floating-point values indeed – however, is it common that users enter such large numbers? I don't think so –, but no rounding error caused by programmer error. >>> int(round(float('9007199254.5'))) 9007199255L >>> int(floor(float('9007199254.5'))) 9007199254L -- PointedEars Bitte keine Kopien per E-Mail. / Please do not Cc: me. -- http://mail.python.org/mailman/listinfo/python-list