読者です 読者をやめる 読者になる 読者になる

Nice angles(CodeEval)

CHALLENGE DESCRIPTION:

Write a program that outputs the value of angle, reducing its fractional part to minutes and seconds.

INPUT SAMPLE:

Write a program that outputs the value of angle, reducing its fractional part to minutes and seconds.

330.39991833
0.001
14.64530319
0.25
254.16991217

OUTPUT SAMPLE:

Print to stdout values of angles with their fractional parts reduced to minutes and seconds.

The whole and fractional parts are separated by period, minutes are separated by apostrophe, seconds by double quotes. The values of minutes and seconds are shown as two numbers (with leading zeros if needed).

330.23'59"
0.00'03"
14.38'43"
0.15'00"
254.10'11"

My Code

#!/usr/bin/env ruby -w

def convert_sexagesimal(decimal)
  hour = decimal.to_i
  tmp_m = (decimal - hour) * 60
  minute = tmp_m.to_i
  tmp_s = (tmp_m - minute) * 60
  second = tmp_s.to_i

  format_sexagesimal(hour, minute, second)
end

def format_sexagesimal(hour, minute, second)
  m = '%02d' % minute
  s = '%02d' % second
  "#{hour}.#{m}'#{s}\""
end

ARGF.each_line do |line|
  puts convert_sexagesimal(line.chomp.to_f)
end