SGhaleb
SGhaleb

Reputation: 1007

Python nearest value digits

I would like to round values to the nearest 10 (0-4 = 0; 5-14 = 1; 15-24=2, etc.) I can get round to nearest 10, but I want to single digits for each range of numbers, as the example shows.

From -5 to 4 = 0, 5 to 14 = 1, 15 to 24 = 2 etc...

What I have tried...

int(math.ceil(x / 10.0)) * 10

This gives to nearest 10, but starts from 0 and gives to nearest 10 instead of single digit.

Any advice is helpful.

Upvotes: 1

Views: 217

Answers (1)

Joe Iddon
Joe Iddon

Reputation: 20414

We can simply use:

int(round(float(x)/10))

From the documentation:

round(number[, ndigits])

Return the floating point value number rounded to ndigits digits after the decimal point. If ndigits is omitted, it defaults to zero. The result is a floating point number. Values are rounded to the closest multiple of 10 to the power minus ndigits; if two multiples are equally close, rounding is done away from 0 (so, for example, round(0.5) is 1.0 and round(-0.5) is -1.0).

Upvotes: 1

Related Questions