Determine precision and scale of particular number in Python

后端 未结 9 1918
野的像风
野的像风 2020-12-09 21:04

I have a variable in Python containing a floating point number (e.g. num = 24654.123), and I\'d like to determine the number\'s precision and scale values (in t

9条回答
  •  独厮守ぢ
    2020-12-09 21:34

    Not possible with floating point variables. For example, typing

    >>> 10.2345
    

    gives:

    10.234500000000001
    

    So, to get 6,4 out of this, you will have to find a way to distinguish between a user entering 10.2345 and 10.234500000000001, which is impossible using floats. This has to do with the way floating point numbers are stored. Use decimal.

    import decimal
    a = decimal.Decimal('10.234539048538495')
    >>> str(a)
    '10.234539048538495'
    >>>  (len(str(a))-1, len(str(a).split('.')[1]))
    (17,15)
    

提交回复
热议问题