-1

I am trying to write a code that rounds down the start list values to the nearest .25 value. How would I be able to do that? So the first index in the start list is 3.645 and that would be rounded to 3.5 since .0, . 25, 0.5, 0.75 are the only increments for 0.25. Since the last index already is a multiple of 0.25 2 stays as 2.

start = [3.645, 33.54656, 1.77, 1.99, 2]

Expected output:

[3.5, 33.5, 1.75, 1.75, 2]
georgehere
  • 610
  • 3
  • 12

1 Answers1

2

This being Python, there's probably some fancy package that will let you do this, but [int(4*x)/4 for x in start] is one way to do it. You can also do [x - x % .25 for x in start] (the modulus operator does work for non-integer modulus).

However, I notice you had your last number be just 2, rather than 2.0. If you want integers to not be cast as floats, you'll have to do something more complicated, such as [int(x) if int(x) == x else int(4*x)/4 for x in start]. And if you want numbers to be cast as int if they're integers after the rounding, it will have to be even more complicated, such as [x - x%.25 if x%1 > .25 else int(x) for x in start]

Acccumulation
  • 3,491
  • 1
  • 8
  • 12