如何在python中转换数据类型



如何在Python中将150000000转换为150000

这是终端输出

Traceback (most recent call last):
File "D:\Python Programme\PC Parts Prise Monitoring System(PPPMS)\netstar.py", line 12, in <module>
print(int(price))
ValueError: invalid literal for int() with base 10: '150,000.00'

我查看了您的错误消息,这解释了您收到错误的原因。

您正在执行print(int(price)),从您的错误中可以看出,您没有将float转换为int,而是将str转换为int。通常情况下,即使这样也应该有效,但您的str有一个,

像这样的问题已经有了答案,这是一个很好的答案。

您必须更改上面答案中的代码以匹配您的区域设置,以便根据您使用的货币/货币系统进行转换。

现在,如果确信只想忽略所有逗号(,(,那么可以使用int(float(price.replace(',','')))

假设,用于分隔千位,.用于分隔小数点:

我的方法是删除"并强制转换为float,从float转换为int(只删除小数点(:

def convert_text_to_int(text):
return int(float(val.replace(',','')))
print(convert_text_to_int(150,000.99)) # 150000

但模块可能会为您做得更好。

与上面类似,但没有双重数据类型转换

def to_int(value:str) -> int:
# return value.replace(",",'').replace(".","")
# I simply replace all commas and dots with empty strings
value = value.replace(",",'')
return round(float(value)) 

编辑:评论行

最新更新