我正在读取一些数据,其中输出(如果是数字)始终存储为浮点型,并且我想清理它,如果实际上可能(例如1.0),则为其分配一个整数,或者如果不可能,则保留原始类型。
使用 try/catch 是最好的方法吗?
function convertToIntIfPossible(x)
try
return convert(Int64,x)
catch
return x
end
end
anInt = convertToIntIfPossible(1.0)
aFloat = convertToIntIfPossible(1.23)
aString = convertToIntIfPossible("aaa")
编辑:这(来自 crstnbr 答案)要快得多:
function convertToIntIfPossible2(x)
if typeof(x) <: Number
if isinteger(x)
return convert(Int64,x)
else
return x
end
else
return x
end
end
EDIT2:这甚至更快(tk Alexander Morley):
function convertToIntIfPossible2(x)
if typeof(x) <: Number
if (x == trunc(x))
return Int64(x)
else
return x
end
else
return x
end
end
最佳答案
重点关注您的问题标题“如何检查整数值是否已保存在 float 中?”,我想给出直接的答案isinteger(x)
。
isinteger(x) -> Bool
Test whether x is numerically equal to some integer.
julia> isinteger(4.0) true
示例:
julia> IntInDisguise = 3.0
3.0
julia> ReallyFloat = 3.141
3.141
julia> ReallyInteger = 3
3
julia> isinteger(IntInDisguise)
true
julia> isinteger(ReallyFloat)
false
julia> isinteger(ReallyInteger)
true
关于casting - 如何检查整数值是否已保存在 float 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48659805/