Convert a string to integer with decimal in Python

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

    The expression int(float(s)) mentioned by others is the best if you want to truncate the value. If you want rounding, using int(round(float(s)) if the round algorithm matches what you want (see the round documentation), otherwise you should use Decimal and one if its rounding algorithms.

提交回复
热议问题