【发布时间】:2021-03-18 07:12:08
【问题描述】:
我想复制python函数int()的功能,它可以将string或float转换为基数为10的int类型。
参考:https://www.w3schools.com/python/ref_func_int.asp
我已经开发了一个小代码来执行这个执行:
a = "5.9"
print("Type of a = ", typeof(a))
if typeof(a) == String
x1 = reinterpret(Int64, a) # 1st attempt
x1 = parse(Int, a) # 2nd attempt
else
x1 = floor(Int64, a)
end
print("\nx1 = $x1", ",\t","type of x1 = ", typeof(x1))
在上面的代码中,我展示了将字符串转换为int 类型的函数,但都不起作用。
请提出一个可以将string 转换为int 的解决方案以及优化上述代码的任何建议?
谢谢!
【问题讨论】:
-
由于
a = "5.9"不是 Int 类型,您应该尝试将其解析为例如。首先使用 Float64,然后应用适当的舍入函数,如下所示:Int(round(parse(Float64, "5.9")))。 -
在 python 中(请参阅您的参考链接)'int' 不适用于“5.9”并给出以下错误。 ValueError: int() 以 10 为底的无效文字:'5.9'
-
@mapi1 感谢您的建议,现在可以使用了!!!非常感谢!!
-
@callmeSteve 是的,同意,python 中的
int不能转换 float-type string 它只适用于 int-type string 即@987654333 @.
标签: string type-conversion integer julia