How can I use python round to int for rounding numbers to the nearest integer?
I’ve been trying to round long float numbers, such as:
32.268907563
32.268907563
31.2396694215
33.6206896552
…
But I’ve had no success so far. I tried using math.ceil(x)
and math.floor(x) (although these roundup or down, which is not what I’m looking for), and I also tried round(x), but it still resulted in float numbers.
Here’s my code:
for i in widthRange:
for j in heightRange:
r, g, b = rgb_im.getpixel((i, j))
h, s, v = colorsys.rgb_to_hsv(r/255.0, g/255.0, b/255.0)
h = h * 360
int(round(h))
print(h)
How can I correctly round these values to the nearest integer using Python round to int?
The round() function returns a float by default, but you can cast the result to int to ensure the output is an integer.
for i in widthRange:
for j in heightRange:
r, g, b = rgb_im.getpixel((i, j))
h, s, v = colorsys.rgb_to_hsv(r/255.0, g/255.0, b/255.0)
h = h * 360
h = int(round(h)) # Round and cast to int
print(h)
This ensures that h is rounded to the nearest integer and converted to an integer type.
Although the round()
function rounds to the nearest integer, you can also combine it with math.trunc()
to remove any fractional part after rounding, which ensures that the result is an integer.
import math
for i in widthRange:
for j in heightRange:
r, g, b = rgb_im.getpixel((i, j))
h, s, v = colorsys.rgb_to_hsv(r/255.0, g/255.0, b/255.0)
h = h * 360
h = math.trunc(round(h)) # Round and truncate to ensure it's an int
print(h)
If you want more control over rounding up or down, you can use math.ceil()
or math.floor()
for rounding, followed by casting to int. For example:
import math
for i in widthRange:
for j in heightRange:
r, g, b = rgb_im.getpixel((i, j))
h, s, v = colorsys.rgb_to_hsv(r/255.0, g/255.0, b/255.0)
h = h * 360
h = int(math.ceil(h)) # Round up and cast to int
print(h)
Or for rounding down:
h = int(math.floor(h)) # Round down and cast to int