0

I am trying to round up the right hand side (fractional part) of a float.

I want to round it up to 5

x = 0.43

expected outcome

0.45 

I can convert the float into an int and then split the string by "." and then round the right hand side of the decimal point but I dont think this is the best method available.

Is there a function available for this type of task?

Thanks

kojiro
  • 74,557
  • 19
  • 143
  • 201
Boosted_d16
  • 13,340
  • 35
  • 98
  • 158

1 Answers1

0

This function will give you the desired output.

def round_to(n, precision=0.5):
    correction = 0.5 if n >= 0 else -0.5
    return int(n/precision+correction)*precision

If you call it:

>>> round_to(0.43)
0.45

I got this function from Python - Round to nearest 05

Community
  • 1
  • 1
Lily Mara
  • 3,859
  • 4
  • 29
  • 48
  • Can this handle something like 0.06? I would want that round up to 0.10 but I'm guessing this func will round it to 0.00 – Boosted_d16 Apr 04 '14 at 14:53
  • If you call this as `round_to(0.06)`, it will return `0.05`, as that is the nearest `0.05`, but if you call it as `round_to(0.06, 0.10)`, it will return `0.1` – Lily Mara Apr 04 '14 at 14:55