简体   繁体   中英

Round float to x decimals?

Is there a way to round a python float to x decimals? For example:

>>> x = roundfloat(66.66666666666, 4)
66.6667
>>> x = roundfloat(1.29578293, 6)
1.295783

I've found ways to trim/truncate them (66.666666666 --> 66.6666), but not round (66.666666666 --> 66.6667).

I feel compelled to provide a counterpoint to Ashwini Chaudhary's answer. Despite appearances, the two-argument form of the round<\/code> function does not<\/em> round a Python float to a given number of decimal places, and it's often not the solution you want, even when you think it is. Let me explain...

The beguilingly simple answer round(x, number_of_places)<\/code> is something of an attractive nuisance: it looks<\/em> as though it does what you want, but thanks to the fact that Python floats are stored internally in binary, it's doing something rather subtler. Consider the following example:

>>> round(52.15, 1)
52.1

Use the built-in function round()<\/code> :

In [23]: round(66.66666666666,4)
Out[23]: 66.6667

In [24]: round(1.29578293,6)
Out[24]: 1.295783

The Mark Dickinson answer, although complete, didn't work with the float(52.15) case. After some tests, there is the solution that I'm using:

import decimal
        
def value_to_decimal(value, decimal_places):
    decimal.getcontext().rounding = decimal.ROUND_HALF_UP  # define rounding method
    return decimal.Decimal(str(float(value))).quantize(decimal.Decimal('1e-{}'.format(decimal_places)))

Default rounding in python and numpy:

In: [round(i) for i in np.arange(10) + .5]
Out: [0, 2, 2, 4, 4, 6, 6, 8, 8, 10]

I coded a function (used in Django project for DecimalField) but it can be used in Python project :

  • <\/li>
  • <\/li>
  • <\/li><\/ul>

    Code with tests :

def trim_to_a_point(num, dec_point):
   
    factor = 10**dec_point # number of points to trim
    num = num*factor # multiple
    num = int(num) # use the trimming of int 
    num = num/factor #divide by the same factor of 10s you multiplied 
    
    return num


#test
a = 14.1234567
trim_to_a_point(a, 5)

output
========
14.12345
  1. multiple by 10^ decimal point you want

  2. truncate with int() method

  3. divide by the same number you multiplied before

  4. done!

Just posted this for educational reasons i think it is correct though:)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM