[Ruby]小数点が含まれる文字列を数値に変換する

書式
対象文字列.to_f()
使用例

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
#!/usr/bin/ruby
#クラスSampleの定義
class Sample
#初期化
def initialize
@num = "12.345"
end
#文字列を小文字に変換
def funcA
p @num.to_f()
p @num.to_f() +1
p "012.3".to_f()
p "012.3".to_f()+2
end
end
#インスタンスを作成
cft = Sample.new
# funcAを呼び出す
cft.funcA
#!/usr/bin/ruby #クラスSampleの定義 class Sample #初期化 def initialize @num = "12.345" end #文字列を小文字に変換 def funcA p @num.to_f() p @num.to_f() +1 p "012.3".to_f() p "012.3".to_f()+2 end end #インスタンスを作成 cft = Sample.new # funcAを呼び出す cft.funcA
#!/usr/bin/ruby
#クラスSampleの定義
class Sample
 #初期化
  def initialize
    @num = "12.345"
  end

 #文字列を小文字に変換
  def funcA
    p @num.to_f()
    p @num.to_f() +1
    p "012.3".to_f()
    p "012.3".to_f()+2
  end

end

#インスタンスを作成
cft = Sample.new

# funcAを呼び出す
cft.funcA

実行結果
12.345
13.345
12.3
14.3

Ruby

Posted by arkgame