Convert a string to integer with decimal in Python

后端 未结 7 1150
余生分开走
余生分开走 2020-11-29 03:33

I have a string in the format: \'nn.nnnnn\' in Python, and I\'d like to convert it to an integer.

Direct conversion fails:

>>> s = \'23.4567         


        
7条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-29 03:40

    How about this?

    >>> s = '23.45678'
    >>> int(float(s))
    23
    

    Or...

    >>> int(Decimal(s))
    23
    

    Or...

    >>> int(s.split('.')[0])
    23
    

    I doubt it's going to get much simpler than that, I'm afraid. Just accept it and move on.

提交回复
热议问题