Convert a string to integer with decimal in Python

后端 未结 7 1153
余生分开走
余生分开走 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:53

    round(float("123.789"))
    

    will give you an integer value, but a float type. With Python's duck typing, however, the actual type is usually not very relevant. This will also round the value, which you might not want. Replace 'round' with 'int' and you'll have it just truncated and an actual int. Like this:

    int(float("123.789"))
    

    But, again, actual 'type' is usually not that important.

提交回复
热议问题