how to convert a fraction to float in ruby

后端 未结 4 1810
盖世英雄少女心
盖世英雄少女心 2021-02-14 17:28

I have a string \"1/16\" I want to convert it to float and multiply it by 45. However, I dont get the desired results.

I am trying in

4条回答
  •  一整个雨季
    2021-02-14 17:55

    Looks like you're going to have to parse the fraction yourself. This will work on fractions and whole numbers, but not mixed numbers (ie: 1½ will not work.)

    class String
      def to_frac
        numerator, denominator = split('/').map(&:to_f)
        denominator ||= 1
        numerator/denominator
      end
    end
    
    "1/16".to_frac * 45
    

提交回复
热议问题