我想将多个十进制数字作为字符串转换为浮动一次性。我正在尝试下面的代码,将这些字符串组合成一个系列,然后将它们转换为浮点数。这样可以正常工作,但如果出现错误则会失败:
a: "1.5"
b: ""
c: "3.7"
invars: [a b c]
print a
print type? a
set invars foreach x invars [append [] to-float reduce x] ; code to convert string series to float series;
print a
print type? a
错误是:
*** Script Error: cannot MAKE/TO float! from: ""
*** Where: to
*** Stack: to-float
为了纠错,我尝试了以下代码:
temp: []
foreach x invars [
y: copy ""
either error? [set [y] to-float reduce x]
[append temp reduce x] ; put original value if not convertable
[append temp reduce y] ]
print temp
set invars temp
print a
print type? a
但这也行不通。问题在哪里以及如何纠正?
答案 0 :(得分:2)
forall invars [invars/1: load get invars/1]
>> invars
== [1.5 [] 3.7]
如果你想摆脱空座
>> replace/all invars block! 0
== [1.5 0 3.7]
如果你真的想在(:less :)步骤中做所有事情
forall invars [invars/1: either empty? invars/1: get invars/1 [0.0] [load invars/1]]
您可以再次设置变量。
但是如果你想设置你的变量,你必须做
foreach x invars [set :x load get x]
使用to-float
foreach x invars [either empty? get x [set :x 0] [set :x to-float get x]]
最后是一个带有to-float的所有错误安全版本
foreach x invars [attempt [set :x to-float get x]]
== 3.7
>> a
== 1.5
>> b
== ""
>> c
== 3.7