我想find和convert一个CSV文件十进制,例如,所有的科学记数法字符串:
1.0e-05 to 0.00001
Run Code Online (Sandbox Code Playgroud)
我怎么能在红宝石中做到这一点?
Pet*_*ter 24
只需使用字符串转换.浮动的必要强制将自动完成:
"%f" % "1.0e-05"
=> "0.000010"
# Which, behind the scenes is the same as:
"%f" % "1.0e-05".to_f
=> "0.000010"
Run Code Online (Sandbox Code Playgroud)
根据需要进行调整以获得更高或更低的准确度 例如:
"%.5f" % "1.0e-05"
=> "0.00001"
Run Code Online (Sandbox Code Playgroud)
如果你想获得真正的幻想,并在最后砍掉不必要的零,这是一种方式.(希望有人会建议更优雅的东西;我想不出任何东西):
("%.20f" % "1.0e-05").sub(/\.?0*$/, "")
=> "0.00001"
Run Code Online (Sandbox Code Playgroud)
如果你有兴趣对数字进行任何数学计算而且它太小了:
"%f" % "1.0e-10"
=> "0.000000"
# not so good for various reasons
("%f" % "1.0e-10") == ("%f" % "1.0e-8")
=> true
Run Code Online (Sandbox Code Playgroud)
你可以使用BigDecimal:
BigDecimal.new "1.0e-10"
=> #<BigDecimal:7ffdf6c38678,'0.1E-9',9(18)>
Run Code Online (Sandbox Code Playgroud)