0

If I have a float like 32.879, and I want to end up with just 0.879, I can think of a few ways to do it, like:

  • Convert to string, strip off everything before the ., convert back to float; OR
  • 32.879 - int(32.879)

Both of those feel like hacks. Is there no pure math operation that can do this?

Sort of like using abs() instead of if x < 0: x = x*-1

I'm dealing with Python, but if anyone can tell me the math name for this operation, I can probably google the Python way to do it.

John
  • 2,551
  • 3
  • 30
  • 55
  • 1
    `math.modf`, or see linked dupe. – tzaman Aug 04 '20 at 18:16
  • 1
    Shortest way is `x%1`, but it depends what behaviour you expect for negative numbers. – khelwood Aug 04 '20 at 18:17
  • 1
    @VisheshMangla converting a float to a string, doing string manipulation, and converting it back to a float is as inefficient, and hacky as it gets. Casting the number to an int, and subtracting it from the original is a roundabout way of doing it. `math.modf` is what I was looking for. Thanks guys – John Aug 04 '20 at 18:20
  • `abs(math.modf(x)[0])`. Seems to work fine. Is there a generic math name for this operation that isn't tied to any programming language? – John Aug 04 '20 at 18:24
  • @John if you only need the fractional part I'd also consider `x % 1` as a more concise way of expressing it. I'm not sure there's a generic term for it beyond "splitting into integer and fractional parts" -- `modf` is the name for this function for this in the original C math library. Maybe also see [this discussion](https://stackoverflow.com/questions/58986957/what-is-modf-a-math-function-from-c-c-etc-shorthand-for) for some etymology. – tzaman Aug 04 '20 at 18:30
  • Yup - `x % 1` works too, and is shorter. Thanks guys! – John Aug 04 '20 at 18:32

0 Answers0