Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python3 How to round up(down) by a certain precision

I need to round up a floating-point number. For example 4.00011 . The inbuilt function round() always rounds up when the number is > .5 and rounds down when <= 5. This is very good. When I want to round something up (down) I import math and use the function math.ceil() (math.floor()). The downside is that ceil() and floor() have no precision "settings". So as an R programmer I would basically just write my own function:

def my_round(x, precision = 0, which = "up"):   
    import math
    x = x * 10 ** precision
    if which == "up":
        x = math.ceil(x)
    elif which == "down":
        x = math.floor(x)
    x = x / (10 ** precision)
    return(x)

my_round(4.00018, 4, "up")

this prints 4.0002

my_round(4.00018, 4, "down")

this prints 4.0001

I can't find a question to this (why?). Is there any other module or function I've missed? Would be great to have a huge library with basic (altered) functions.

edit: I do not talk about integers.


1 Answers

Check out my answer from this SO post. You should be able to easily modify it to your needs by swapping floor for round.

Please let me know if that helps!


EDIT I just felt it, so I wanted to propose a code based solution

import math

def round2precision(val, precision: int = 0, which: str = ''):
    assert precision >= 0
    val *= 10 ** precision
    round_callback = round
    if which.lower() == 'up':
        round_callback = math.ceil
    if which.lower() == 'down':
        round_callback = math.floor
    return '{1:.{0}f}'.format(precision, round_callback(val) / 10 ** precision)


quantity = 0.00725562
print(quantity)
print(round2precision(quantity, 6, 'up'))
print(round2precision(quantity, 6, 'down'))

which yields

0.00725562
0.007256
0.007255
like image 193
tahesse Avatar answered Jul 17 '26 22:07

tahesse



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!