Ruby : Utility Numeric

Untuk membulatkan bilangan

x #bilangan yang akan dibulatkan
y #bilangan pembulat :p

pembulat = 1.to_f / y.to_f
hasil = (x * pembulat).round.to_f / pembulat


Untuk membuat pembulatan keatas / kebawah
ganti round dengan ceil atau floor

pembulatan keatas
pembulat = 1.to_f / y.to_f
hasil = (x * pembulat).ceil.to_f / pembulat


pembulatan kebawah
pembulat = 1.to_f / y.to_f
hasil = (x * pembulat).floor.to_f / pembulat


lebih lengkapnya, beginilah isi dari modul yang saya pakai
hasil copy paste dari internet dan edit sana sini

module Utils
def get_float(val)
begin
tmp = Float(val)
return tmp
rescue
return 0.to_f
end
end

def get_integer(val)
begin
tmp = Integer(val)
return tmp
rescue
return 0
end
end

def round_to(x)
(self * 10**x).round.to_f / 10**x
end

def ceil_to(x)
(self * 10**x).ceil.to_f / 10**x
end

def floor_to(x)
(self * 10**x).floor.to_f / 10**x
end

def round_by(number,rounder)
round = 1.to_f / get_float(rounder)
calc = (number.to_f * round).round.to_f / round
return calc
end

def ceil_by(number,rounder)
round = 1.to_f / get_float(rounder)
calc = (number.to_f * round).ceil.to_f / round
return calc
end

def floor_by(number,rounder)
round = 1.to_f / get_float(rounder)
calc = (number.to_f * round).floor.to_f / round
return calc
end

0 Comments:

Post a Comment