Petros Kyriakou
Petros Kyriakou

Reputation: 5343

Input number multiplies as a string instead of number - Rails 4

I want you to focus on the line conversion = value * 7.50061

Consider the following. When i print the conversion with an initial value of 12, i get seven times 12 like this 12121212121212 . Propably thats because i am multiplying a string but when i tried

value.to_i i had an error saying implicit conversion from float to string??

i submit a value from an input element in the view and i input it from the CalculationsController to the CalculationsHelper

module CalculationsHelper

  # parameter1 = Sa02, parameter2 = Hgb, parameter3  = PaO2
  def AOC(parameter1,parameter2,parameter3,unit_parameter2,unit_parameter3)
    # CaO2 = ( Hgb * 1.34 * SaO2 / 100 ) + ( PaO2 * 0.031 )
    if (unit_parameter3 != "mmHg")
      puts "entered conversions"
      conversions(unit_parameter3,parameter3, "mmHg")
    end
  end

  def conversions(input, value, target)
    if (target == "mmHg")
      if (input == "Kpa")
        puts "this is the value before " + value
        conversion = value * 7.50061
        puts "this is the " + conversion
      end
    end
  end

end

CalculationsController

class CalculationsController < ApplicationController
  include CalculationsHelper

  def index

  end

  def calculation

    if (params["equation"] == "AOC")
      puts "entered AOC"
      AOC(params["parameter1"],params["parameter2"],params["parameter3"],params["unit_parameter2"],params["unit_parameter3"])
    end
    respond_to do |format|
      format.json {
        render json: { success: "ok" }
      }
    end
  end
end

any help appreciated

Upvotes: 0

Views: 73

Answers (2)

spickermann
spickermann

Reputation: 106972

You are on the right track, you first need to cast the string value to an float or integer to do calculation with it. If the String is 12 it probably makes more sense to cast it to an integer:

conversion = value.to_i * 7.50061

The you get the implicit conversion from float to string error in the next line ("this is the " + conversion), because you try to add a float to a string.

Write instead:

puts "this is the #{conversion}"

Upvotes: 1

Andrey Deineko
Andrey Deineko

Reputation: 52357

conversion = value.to_f * 7.50061

Upvotes: 0

Related Questions