(python) Recreation of round function algorithms. rounding off a decimal point

Asked 1 years ago, Updated 1 years ago, 342 views

I'm trying to recreate the round function algorithm, but I'm not sure about the decimal range processing part. That's what we've done so far.

def my_round(number, ndgits=None):
    if number<0: return int(number +0.5) -1
    return int(number - 0.5)+1

test = 1.74789
a=my_round(test)
print(a)

This will allow normal integer rounding, but there is no rounding setting to a decimal point. How do I code without using other functions?

python

2022-11-09 09:43

2 Answers

You can make them respond to decimal places.

By the way, is there a reason why the basic function is made into a code?

def a(number, ndgits = 1):
    ndgits = 5 * 0.1**ndgits
    print(ndgits)
    a, b = divmod(number, ndgits)
    print(a, b)
    if a % 2:
        return int(number) + 1
    else:
        return int(number)
b = 0.8
c = a(b, 3)
print(c)


2022-11-09 15:01

Implement without other functions

def my_round(number, ndgits=1):
    return int((number*(10**ndgits) + (- 5 if number < 0 else 5))/10)/(10**(ndgits-1))

test = 1.74789
print(my_round(test,1)) #2.0
print(my_round(test,2)) #1.7
print(my_round(test,3)) #1.75
print(my_round(test,4)) #1.748


2022-11-09 16:05

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.