Spring til indhold

Modul:Sexagesimal

Fra Wikipedia, den frie encyklopædi

-- Module for converting a decimal angle into sexagesimal units

local p = {} 

local function IntDiv(Nomin, Denom)		-- Integer division
	return math.floor(Nomin/Denom)
end	-- IntDiv

function p.sexagesimal (frame)
	-- Parameters:
	-- frame.args is an array of parameters taken from the calling #invoke-statement
	-- frame.args[1]: Decimal number to be converted
	-- frame.args[2]: Requiered number of decimals in the seconds value (0 to 9)
	-- frame.args[3]: Conversion format with three allowed values:
	--		DD: DegToDMS. Output: Sign, degree, arcminute and arcsecond; + − ° ′ ″
	--		DH: DegToHMS. Output: Degrees converted to hour measure: Hour, time minute and time second; h m s
	--		HH: HrsToHMS. Output: Hour, time minute and time second; h m s
	-- Finds values for Degree/Hour (integer), Minute (integer) and Second (real)
	-- Rounding MUST occur at the beginning to avoid abominations such as 12:34:60

	local Degrees = tonumber(frame.args[1])
	local Decimals = tonumber(frame.args[2])
	local Selector = mw.text.trim(frame.args[3])
	local Sign

	if Selector == "DH" then Degrees = Degrees/15 end 
	if Selector == "DD" then
		if Degrees > 0 then 
			Sign = "+"
		elseif Degrees < 0 then
			Sign = "−"
		else
			Sign = "&nbsp;"
		end
	end
	Degrees = math.abs(Degrees)

	local TenPower = 10^Decimals
	local Factor = 3600*TenPower
	local I = math.floor(Factor*Degrees + 0.5)	-- Rounding
	local H = IntDiv(I, Factor) 
	I = I - Factor*H
	Factor = 60*TenPower
	local M = math.floor(I/Factor)         --IntDiv(I, Factor)
	-- local M = p.IntDiv(I, Factor)
	local S = I/TenPower - 60*M

	-- Return result
	local FormatStr
	if Selector == "DD" then 
		if Decimals == 0 then
			FormatStr = "%s&nbsp;%02d°&nbsp;%02d′&nbsp;%02d″"
		else
			FormatStr = "%s&nbsp;%02d°&nbsp;%02d′&nbsp;%0" .. Decimals + 3 .. "." .. Decimals .. "f″"
		end
		return string.format (FormatStr, Sign,H,M,S)
	else
		if Decimals == 0 then
			FormatStr = "%02d<sup>h</sup>&nbsp;%02d<sup>m</sup>&nbsp;%02d<sup>s</sup>"
		else
			FormatStr = "%02d<sup>h</sup>&nbsp;%02d<sup>m</sup>&nbsp;%0" .. Decimals + 3 .. "." .. Decimals .."f<sup>s</sup>"
		end
		return string.format (FormatStr, H,M,S) 
	end
end -- p.sexagesimal

return p