0

I have a float numer

a = 1.263597

I hope get

b = 1.2635

But when I try

round (a,4)

then result is

1.2636

What should I do?

1
  • Why are you expecting "1.2635" when the normal rounding rules should get you "1.2636", since there's a "9" after the "5"? Commented Dec 6, 2022 at 16:24

3 Answers 3

1

Try math.floor with this small modification -

import math

def floor_rounded(n,d):
    return math.floor(n*10**d)/10**d

n = 1.263597
d = 4

output = floor_rounded(n,d)
print(output)
1.2635

For your example, you can just do math.floor(1.263597 * 10000)/10000


EDIT: Based on the valid comment by @Mark, here is another way of solving this, but this time forcing the custom rounding using string operations.

#EDIT: Alternate approach, based on the comment by Mark Dickinson

def string_rounded(n,d):
    i,j = str(n).split('.')
    return float(i+'.'+j[:d])

n = 8.04
d = 2

output = string_rounded(n,d)
output
8.04
Sign up to request clarification or add additional context in comments.

2 Comments

Beware corner cases arising from the What You See Is Not What You Get nature of binary floating-point. E.g., floor_rounded(8.04, 2) gives 8.03 on my machine (and floor_rounded(8.03, 2) gives 8.02, so the rounding operation isn't even idempotent).
Thanks for the feedback! Completely agree with your point above, have added a method using string manipulations which should avoid this.
1

Plain Python without importing any libraries (even not standard libraries):

def round_down(number, ndigits=None):
    if ndigits is None or ndigits == 0:
        # Return an integer if ndigits is 0
        return int(number)
    else:
        return int(number * 10**ndigits) / 10**ndigits

a = 1.263597
b = round_down(a, 4)
print(b)
1.2635

Note that this function rounds towards zero, i.e. it rounds down positive floats and rounds up negative floats.

Comments

0
def round_down(number, ndigits=0):
    return round(number-0.5/pow(10, ndigits), ndigits)

Run:

round_down(1.263597, 4)
>> 1.2635

2 Comments

That's not a good idea. Rounding down, which seems to be what the OP wants, is not the same as rounding a smaller number.
Right, but there is a trick of adding/subtracting 0.5 to any number when wanting to round up/down that is useful for a fraction of half too

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.