次の番号のいずれかがあるとします。
230957 または 83487 または 4785
Rubyでそれぞれ300000または90000または5000として返す方法は何ですか?
次の番号のいずれかがあるとします。
230957 または 83487 または 4785
Rubyでそれぞれ300000または90000または5000として返す方法は何ですか?
def round_up(number)
divisor = 10**Math.log10(number).floor
i = number / divisor
remainder = number % divisor
if remainder == 0
i * divisor
else
(i + 1) * divisor
end
end
あなたの例で:
irb(main):022:0> round_up(4785)
=> 5000
irb(main):023:0> round_up(83487)
=> 90000
irb(main):024:0> round_up(230957)
=> 300000
def round_to_significant_digit(i, significant_digits = 1)
exp = Math.log10(i).floor - (significant_digits - 1)
(i / 10.0 ** exp).round * 10 ** exp
end
>> [230957, 83487, 4785].collect{|i|round_to_significant_digit(i)}
=> [200000, 80000, 5000]
追加のクレジットについては、次のとおりです。
>> [230957, 83487, 4785].collect{|i|round_to_significant_digit(i, 2)}
=> [230000, 83000, 4800]
>> [230957, 83487, 4785].collect{|i|round_to_significant_digit(i, 3)}
=> [231000, 83500, 4790]
Rails では、"number_to_human" ヘルパーも気に入るかもしれません。このヘルパーは、適切な次元を自動的に選択して丸めます。
http://api.rubyonrails.org/classes/ActionView/Helpers/NumberHelper.html#method-i-number_to_human
実際にRubyでコーディングしたことはありませんが、最初に必要な桁に押し込めば、標準の丸め関数でそれを行うことができます.
例:
230957 / 100000(the resolution you want) = 2.30957
Round 2.30957 = 2、または Round to Ceiling/Round 値+ 0.5を使用して、下限値ではなく上限値に移動します。
2 or 3 * 100000(the resolution you want) = 200000 or 300000 respectively.
お役に立てれば!
少し醜いように見えますが、最初のショットとして(毎回切り上げます)...
>> (("230957".split("").first.to_i + 1).to_s + \
("0" * ("230957".size - 1))).to_i
=> 300000
より良い(正しいラウンド):
>> (230957 / 10 ** Math.log10(230957).floor) * \
10 ** Math.log10(230957).floor
=> 200000
簡単な提案:
def nearest_large_number value
str = value.to_s.gsub(/^([0-9])/) { "#{$1}." }
multiplicator = ("1" + "0" * str.split('.')[1].length).to_i
str.to_f.ceil * multiplicator
end
使用するには:
nearest_large_number 230957
=> 300000