Search code examples
pythonfloating-pointcurrencyrounding

rounding float up $.01 in python


I am working on a program that stores numbers as floats which I eventually write to a file as currency. I am currently using the round() function to round it to 2 decimals, but the business area would like me to round to the next penny no matter what the third decimal is. For example:

x = 39.142

In this case I am trying to get x to round up to 39.15. Obviously when I do the round function I get 39.14...

>>> round(x, 2)
    39.14

Is there a way I can always round up to the next penny? I should mention that the numbers I am dealing with are printed to the file as currency.


Solution

  • Using the decimal module:

    import decimal
    D = decimal.Decimal
    cent = D('0.01')
    
    x = D('39.142')
    print(x.quantize(cent,rounding=decimal.ROUND_UP))
    # 39.15
    

    Decimals have many options for rounding. The options and their meanings can be found here.