圆形浮动到Ruby最近的四分之一

时间:2016-10-17 15:56:22

标签: ruby-on-rails ruby floating-point

我在Ruby on Rails应用程序中使用外部api。我需要将浮动信息发送给该公司,但他们只接受1.01.251.51.752.0等值。

我的值可能为1.341.80。理想情况下,我需要将它们四舍五入到最近的0.25。什么是实现这一目标的最佳方法?如果我1.34.round(0)它会给我1.0,这比我需要的要低。

谢谢!

2 个答案:

答案 0 :(得分:16)

(1.27 * 4).round / 4.0
#=> 1.25

如果您经常使用它,那么对Float类进行修补是非常有意义的,以便更简单地使用它:

class Float
  def round_to_quarter
    (self * 4).round / 4.0
  end
end
1.27.round_to_quarter
#=> 1.25
1.52.round_to_quarter
#=> 1.5
1.80.round_to_quarter
#=> 1.75
1.88.round_to_quarter
#=> 2.0

答案 1 :(得分:-3)

虽然如果您对monkey patching主要红宝石课程不满意,安德烈的解决方案仍然有效,以下内容也适用

# import some packages
from numpy import array
import xml.etree.ElementTree as et

# init some lists
ids=[]
depart=[]
arrival=[]
duration=[]
distance=[]

# prep the xml document
xmltxt = """
    <root>
        <tripinfo id="1" depart="1.00" arrival="2" duration="1.00" distance="3"/>
        <tripinfo id="5" depart="2.00" arrival="4" duration="2.00" distance="5"/>
        <tripinfo id="3" depart="3.00" arrival="6" duration="3.00" distance="2"/>
        <tripinfo id="10" depart="5.00" arrival="8" duration="3.00" distance="1"/>
        <tripinfo id="8" depart="8.00" arrival="10" duration="2.00" distance="4"/>
    </root>
"""

# parse the xml text
xmldoc = et.fromstring(xmltxt)

# extract and output tripinfo attributes
# collect them into lists
for item in xmldoc.iterfind('tripinfo'):
    att=item.attrib
    ids.append(int(att['id']))
    depart.append(float(att['depart']))
    arrival.append(float(att['arrival']))
    duration.append(float(att['duration']))
    distance.append(float(att['distance']))

# put lists into an np.array
# and transpose it    
arr=array([ids, depart, arrival, duration, distance]).T

# sort array by 'depart' column. (index=1)
arr = arr[arr[:,1].argsort()]

sumdist=0
dept=0
print "depart: %s; Sum_dist= %s" % ( dept, sumdist )
for ea in arr:
    sumdist += ea[4] # distance
    dept = ea[1]  # depart
    # get 'arrival', 'duration' here, so that
    # you can use them to manipulate and get your exact solution
    print "depart: %s; Sum_dist= %s" % ( dept, sumdist )