Modul:ConvertNumeric

Från Wikipedia
Hoppa till navigering Hoppa till sök

Dokumentationen för denna modul kan skapas på Modul:ConvertNumeric/dok

-- Modul för konvertering mellan olika representationer av tal.

local ones_position = {
	[0] = 'noll',
	[1] = 'ett',
	[2] = 'två',
	[3] = 'tre',
	[4] = 'fyra',
	[5] = 'fem',
	[6] = 'sex',
	[7] = 'sju',
	[8] = 'åtta',
	[9] = 'nio',
	[10] = 'tio',
	[11] = 'elva',
	[12] = 'tolv',
	[13] = 'tretton',
	[14] = 'fjorton',
	[15] = 'femton',
	[16] = 'sexton',
	[17] = 'sjutton',
	[18] = 'arton',
	[19] = 'nitton'
}

local ones_position_ord = {
	[0] = 'nollte',
	[1] = 'första',
	[2] = 'andra',
	[3] = 'tredje',
	[4] = 'fjärde',
	[5] = 'femte',
	[6] = 'sjätte',
	[7] = 'sjunde',
	[8] = 'åttonde',
	[9] = 'nionde',
	[10] = 'tionde',
	[11] = 'elfte',
	[12] = 'tolfte',
	[13] = 'trettonde',
	[14] = 'fjortonde',
	[15] = 'femtonde',
	[16] = 'sextonde',
	[17] = 'sjuttonde',
	[18] = 'artonde',
	[19] = 'nittonde'
}

local ones_position_plural = {
	[0] = 'noll',
	[1] = 'ett',
	[2] = 'två',
	[3] = 'tre',
	[4] = 'fyra',
	[5] = 'fem',
	[6] = 'sex',
	[7] = 'sju',
	[8] = 'åtta',
	[9] = 'nio',
	[10] = 'tio',
	[11] = 'elva',
	[12] = 'tolv',
	[13] = 'tretton',
	[14] = 'fjorton',
	[15] = 'femton',
	[16] = 'sexton',
	[17] = 'sjutton',
	[18] = 'arton',
	[19] = 'nitton'
}

local tens_position = {
	[2] = 'tjugo',
	[3] = 'trettio',
	[4] = 'fyrtio',
	[5] = 'femtio',
	[6] = 'sextio',
	[7] = 'sjuttio',
	[8] = 'åttio',
	[9] = 'nittio'
}

local tens_position_ord = {
	[2] = 'tjugonde',
	[3] = 'trettionde',
	[4] = 'fyrtionde',
	[5] = 'femtionde',
	[6] = 'sextionde',
	[7] = 'sjuttionde',
	[8] = 'åttionde',
	[9] = 'nittionde'
}

local tens_position_plural = {
	[2] = 'tjugo',
	[3] = 'trettio',
	[4] = 'fyrtio',
	[5] = 'femtio',
	[7] = 'sjuttio',
	[8] = 'åttio',
	[9] = 'nittio'
}

local groups = {
	[1] = 'tusen',
	[2] = 'miljoner',
	[3] = 'miljarder',
	[4] = 'biljoner',
	[5] = 'biljarder',
	[6] = 'triljoner',
	[7] = 'triljarder',
	[8] = 'kvadriljoner',
	[9] = 'kvadriljarder',
	[10] = 'kvintiljoner',
	[11] = 'kvintiljarder',
	[12] = 'sextiljoner',
	[13] = 'sextiljarder',
	[14] = 'septiljoner',
	[15] = 'septiljarder',
	[16] = 'oktiljoner',
	[17] = 'oktiljarder'
}


local roman_numerals = {
	I = 1,
	V = 5,
	X = 10,
	L = 50,
	C = 100,
	D = 500,
	M = 1000
}

-- Konverterar romerska siffror till ett tal. Returnerar -1, felsträng för fel
local function roman_to_numeral(roman)
	if type(roman) ~= "string" then return -1, "roman numeral not a string" end
	local rev = roman:reverse()
	local raising = true
	local last = 0
	local result = 0
	for i = 1, #rev do
		local c = rev:sub(i, i)
		local next = roman_numerals[c]
		if next == nil then return -1, "romerskt tal innehåller otillåtet tecken " .. c end
		if next > last then
			result = result + next
			raising = true
		elseif next < last then
			result = result - next
			raising = false
		elseif raising then
			result = result + next
		else
			result = result - next
		end
		last = next
	end
	return result
end

-- Konverterar ett givet tal mellan 0 och 100 till svenskt räkneord (exempelvis 47 -> fyrtiosju)
local function numeral_to_swedish_less_100(num, ordinal, plural, zero)
	local terminal_ones, terminal_tens
	if ordinal then
		terminal_ones = ones_position_ord
		terminal_tens = tens_position_ord
	elseif plural then
		terminal_ones = ones_position_plural
		terminal_tens = tens_position_plural
	else
		terminal_ones = ones_position
		terminal_tens = tens_position
	end

	if num == 0 and zero ~= nil then
		return zero
	elseif num < 20 then
		return terminal_ones[num]
	elseif num % 10 == 0 then
		return terminal_tens[num / 10]
	else
		return tens_position[math.floor(num / 10)] .. '' .. terminal_ones[num % 10]
	end
end

local function standard_suffix(ordinal, plural)
	if ordinal then return 'de' end
	if plural then return '' end
	return ''
end

-- Konverterar ett givet tal mellan 0 och 1000 till svenskt räkneord (exempelvis 47 -> fyrtiosju)
local function numeral_to_swedish_less_1000(num, use_and, ordinal, plural, zero)
	num = tonumber(num)
	if num < 100 then
		return numeral_to_swedish_less_100(num, ordinal, plural, zero)
	elseif num % 100 == 0 then
		return ones_position[num/100] .. 'hundra' .. standard_suffix(ordinal, plural)
	else
		return ones_position[math.floor(num/100)] .. 'hundra' .. (use_and and '' or '') .. numeral_to_swedish_less_100(num % 100, ordinal, plural, zero)
	end
end

-- Konverterar ett tal uttryckt som en sträng i vetenskaplig notation till en sträng i standardiserad decimalnotation
-- Exempelvis 1.23E5 -> 123000, 1.23E-5 = .0000123. Omvandlingen är exakt, ingen avrundning utförs.
local function scientific_notation_to_decimal(num)
	local exponent, subs = num:gsub("^%-?%d*%.?%d*%-?[Ee]([+%-]?%d+)$", "%1")
	if subs == 0 then return num end  -- Om inte i vetenskaplig notation, sedan tillbaka omodifierad
	exponent = tonumber(exponent)

	local minus = num:find("^%-")
	local _, decimal_pos = num:find("%.")
	-- Mantissa kommer att bestå av alla decimaler utan decimalpunkt
	local mantissa = num:gsub("^%-?(%d*)%.?(%d*)%-?[Ee][+%-]?%d+$", "%1%2")
	if minus and decimal_pos then decimal_pos = decimal_pos - 1 end
	if not decimal_pos then decimal_pos = #mantissa + 1 end
	local prev_len = #num

	-- Tar bort inledande nollor om decimalpunkt är i första position
	while decimal_pos > 1 and mantissa:sub(1,1) == '0' do
		mantissa = mantissa:sub(2)
		decimal_pos = decimal_pos - 1
	end
	-- Skiftar decimalpunkt åt höger för exponent > 0
	while exponent > 0 do
		decimal_pos = decimal_pos + 1
		exponent = exponent - 1
		if decimal_pos > #mantissa + 1 then mantissa = mantissa .. '0' end
		-- Tar bort inledande nollor om decimalpunkt är i första position
		while decimal_pos > 1 and mantissa:sub(1,1) == '0' do
			mantissa = mantissa:sub(2)
			decimal_pos = decimal_pos - 1
		end
	end
	-- Skiftar decimalpunkt åt vänster för exponent < 0
	while exponent < 0 do
		if decimal_pos == 1 then
			mantissa = '0' .. mantissa
		else
			decimal_pos = decimal_pos - 1
		end
		exponent = exponent + 1
	end

	-- Sätter in decimalpunkt i korrekt position och returnerar
	return (minus and '-' or '') .. mantissa:sub(1, decimal_pos - 1) .. '.' .. mantissa:sub(decimal_pos)
end

-- Avrundar ett tal till närmaste heltal (ANVÄNDS INTE)
local function round_num(x)
	if x%1 >= 0.5 then
		return math.ceil(x)
	else
		return math.floor(x)
	end
end

-- Avrundar ett tal till närmaste två-ordstal (round = up, down, eller "on" för att avrunda till närmaste)
-- Tal med två siffror före decimalen avrundas till ett heltal som specificeras av rundan.
-- Större tal avrundas till ett tal med endast en nollskild siffra och alla andra siffror noll.
-- Minustecken bevaras och räknas inte mot ordgräns.
local function round_for_swedish(num, round)
	-- Om ett heltal har högst två siffror, sedan tillbaka
	if num:find("^%-?%d?%d%.?$") then return num end

	local minus = num:find("^%-")
	if minus then
		-- We're rounding magnitude so flip it
		if round == 'up' then round = 'down' elseif round == 'down' then round = 'up' end
	end

	-- If at most two digits before decimal, round to integer and return
	local _, _, small_int, trailing_digits, round_digit = num:find("^%-?(%d?%d?)%.((%d)%d*)$")
	if small_int then
		local small_int_len = #small_int
		if small_int == '' then small_int = '0' end
		if (round == 'up' and trailing_digits:find('[1-9]')) or (round == 'on' and tonumber(round_digit) >= 5) then
			small_int = tostring(tonumber(small_int) + 1)
		end
		return (minus and '-' or '') .. small_int
	end

	-- When rounding up, any number with > 1 nonzero digit will round up (e.g. 1000000.001 rounds up to 2000000)
	local nonzero_digits = 0
	for digit in num:gfind("[1-9]") do
		nonzero_digits = nonzero_digits + 1
	end

	num = num:gsub("%.%d*$", "") -- Remove decimal part
	-- Second digit used to determine which way to round lead digit
	local _, _, lead_digit, round_digit, round_digit_2, rest = num:find("^%-?(%d)(%d)(%d)(%d*)$")
	if tonumber(lead_digit .. round_digit) < 20 and (1 + #rest) % 3 == 0 then
		-- In swedish numbers < 20 are one word so put 2 digits in lead and round based on 3rd
		lead_digit = lead_digit .. round_digit
		round_digit = round_digit_2
	else
		rest = round_digit_2 .. rest
	end

	if (round == 'up' and nonzero_digits > 1) or (round == 'on' and tonumber(round_digit) >= 5) then
		lead_digit = tostring(tonumber(lead_digit) + 1)
	end
	-- All digits but lead digit will turn to zero
	rest = rest:gsub("%d", "0")
	return (minus and '-' or '') .. lead_digit .. '0' .. rest
end

local denominators = {
	[2] = { 'halv', plural = 'halva' },
	[3] = { 'tredjedel', plural = 'tredjedelar' },
	[4] = { 'fjärdedel', plural = 'fjärdedelar' },
	[5] = { 'femtedel', plural = 'femtedelar' },
	[6] = { 'sjättedel', plural = 'sjättedelar' },
	[7] = { 'sjundedel', plural = 'sjundedelar' },
	[8] = { 'åttondel', plural = 'åttondelar' },
	[9] = { 'niondel', plural = 'niondelar' },
	[10] = { 'tiondel', plural = 'tiondelar' },
	[16] = { 'sextondel', plural = 'sextondelar' },
}

-- Return status, fraction where:
-- status is a string:
--     "finished" if there is a fraction with no whole number;
--     "ok" if fraction is empty or valid;
--     "unsupported" if bad fraction;
-- fraction is a string giving (numerator / denominator) as Swedish text, or is "".
-- Only unsigned fractions with a very limited range of values are supported,
-- except that if whole is empty, the numerator can use "-" to indicate minus.
-- whole (string or nil): nil or "" if no number before the fraction
-- numerator (string or nil): numerator, if any (default = 1 if a denominator is given)
-- denominator (string or nil): denominator, if any
-- sp_us (boolean): true if sp=us
-- minus_word (string): word to use for minus sign, if whole is empty
-- use_one (boolean): false: 2+1/2 → "two and a half"; true: "two and one-half"
local function fraction_to_swedish(whole, numerator, denominator, sp_us, minus_word, use_one)
	if numerator or denominator then
		local finished = (whole == nil or whole == '')
		local sign = ''
		if numerator then
			if finished and numerator:sub(1, 1) == '-' then
				numerator = numerator:sub(2)
				sign = minus_word .. ' '
			end
		else
			numerator = '1'
		end
		if not numerator:match('^%d+$') or not denominator or not denominator:match('^%d+$') then
			return 'unsupported', ''
		end
		numerator = tonumber(numerator)
		denominator = tonumber(denominator)
		local dendata = denominators[denominator]
		if not (dendata and 1 <= numerator and numerator <= 99) then
			return 'unsupported', ''
		end
		local numstr, denstr
		local sep = ' '
		if numerator == 1 then
			denstr = sp_us and dendata.us or dendata[1]
			numstr = 'en'
--[[			
			if finished or use_one then
				numstr = 'en'
			elseif denstr:match('^[aeiou]') then
				numstr = 'an'
				sep = ' '
			else
				numstr = 'a'
				sep = ' '
			end
]]			
		else
			numstr = numeral_to_swedish_less_100(numerator)
			denstr = dendata.plural
			if not denstr then
				denstr = (sp_us and dendata.us or dendata[1]) .. 's'
			end
		end
		if finished then
			return 'finished', sign .. numstr .. sep .. denstr
		end
		return 'ok', ' och ' .. numstr .. sep .. denstr
	end
	return 'ok', ''
end

-- Takes a decimal number and converts it to Swedish text.
-- Return nil if a fraction cannot be converted (only some numbers are supported for fractions).
-- num (string or nil): the number to convert.
--      Can be an arbitrarily large decimal, such as "-123456789123456789.345", and
--      can use scientific notation (e.g. "1.23E5").
--      May fail for very large numbers not listed in "groups" such as "1E4000".
--      num is nil if there is no whole number before a fraction.
-- numerator (string or nil): numerator of fraction (nil if no fraction)
-- denominator (string or nil): denominator of fraction (nil if no fraction)
-- capitalize (boolean): whether to capitalize the result (e.g. 'One' instead of 'one')
-- use_and (boolean): whether to use the word 'and' between tens/ones place and higher places
-- hyphenate (boolean): whether to hyphenate all words in the result, useful for use as an adjective
-- ordinal (boolean): whether to produce an ordinal (e.g. 'first' instead of 'one')
-- plural (boolean): whether to pluralize the resulting number
-- links: nil: do not add any links; 'on': link "billion" and larger to Orders of magnitude article;
--        any other text: list of numbers to link (e.g. "billion,quadrillion")
-- minus_word: word to use for minus sign (typically 'minus' or 'minus'; nil to use default)
-- round: nil or '': no rounding; 'on': round to nearest two-word number; 'up'/'down': round up/down to two-word number
-- zero: word to use for value '0' (nil to use default)
-- use_one (boolean): false: 2+1/2 → "two and a half"; true: "two and one-half"
local function _numeral_to_swedish(num, numerator, denominator, capitalize, use_and, hyphenate, ordinal, plural, links, minus_word, round, zero, use_one)
	if not minus_word then
		if use_and then
			-- TODO Should 'minus' be used when do not have sp=us?
			--      If so, need to update testcases, and need to fix "minus zero".
			-- minus_word = 'minus'
			minus_word = 'minus'
		else
			minus_word = 'minus'
		end
	end
	local status, fraction_text = fraction_to_swedish(num, numerator, denominator, not use_and, minus_word, use_one)
	if status == 'unsupported' then
		return nil
	end
	if status == 'finished' then
		-- Input is a fraction with no whole number.
		-- Hack to avoid executing stuff that depends on num being a number.
		local s = fraction_text
		if hyphenate then s = s:gsub("%s", "-") end
		if capitalize then s = s:gsub("^%l", string.upper) end
		return s
	end
	num = scientific_notation_to_decimal(num)
	if round and round ~= '' then
		if round ~= 'on' and round ~= 'up' and round ~= 'down' then
			return 'Invalid rounding mode'
		end
		num = round_for_swedish(num, round)
	end

	-- Separate into minus sign, num (digits before decimal), decimal_places (digits after decimal)
	local MINUS = '−'  -- Unicode U+2212 MINUS SIGN (may be in values from [[Module:Convert]])
	if num:sub(1, #MINUS) == MINUS then
		num = '-' .. num:sub(#MINUS + 1)  -- replace MINUS with '-'
	elseif num:sub(1, 1) == '+' then
		num = num:sub(2)  -- ignore any '+'
	end
	local minus = num:find("^%-")
	local decimal_places, subs = num:gsub("^%-?%d*%.(%d+)$", "%1")
	if subs == 0 then decimal_places = nil end
	num, subs = num:gsub("^%-?(%d*)%.?%d*$", "%1")
	if num == '' and decimal_places then num = '0' end
	if subs == 0 or num == '' then return 'Ogiltigt decimaltal' end

	-- For each group of 3 digits except the last one, print with appropriate group name (e.g. million)
	local s = ''
	while #num > 3 do
--		if s ~= '' then s = s .. ' ' end
		local group_num = math.floor((#num - 1) / 3)
		local group = groups[group_num]
		local group_digits = #num - group_num*3
		s = s .. ' ' .. numeral_to_swedish_less_1000(num:sub(1, group_digits), false, false, false, zero)
		if links and (((links == 'on' and group_num >= 3) or links:find(group)) and group_num <= 13) then
			s = s .. '[[Orders_of_magnitude_(numbers)#10' .. group_num*3 .. '|' .. group .. ']]'
		else
			s = s .. group
		end
		num = num:sub(1 + group_digits)
		num = num:gsub("^0*", "")  -- Trim leading zeros
	end

	-- Handle final three digits of integer part
	--[[
	if s ~= '' and num ~= '' then
		if #num <= 2 and use_and then
			s = s .. ' and '
		else
			s = s .. ' '
		end
	end
	]]
	if s == '' or num ~= '' then
		s = s .. ' ' .. numeral_to_swedish_less_1000(num, use_and, ordinal, plural, zero)
	elseif ordinal or plural then
		-- Round numbers like "one million" take standard suffixes for ordinal/plural
		s = s .. standard_suffix(ordinal, plural)
	end
    s = s:gsub("etttusen","ettusen")
    
	-- For decimal places (if any) output "komma" followed by spelling out digit by digit
	if decimal_places then
		s = s .. ' komma'
		for i = 1, #decimal_places do
			s = s .. ' ' .. ones_position[tonumber(decimal_places:sub(i,i))]
		end
	end

	s = s:gsub("^%s*(.-)%s*$", "%1")   -- Trim whitespace
	if ordinal and plural then s = s .. 's' end  -- s suffix works for all ordinals
	if minus and s ~= zero then s = minus_word .. ' ' .. s end
	s = s:gsub("minus zero", "zero")
	s = s .. fraction_text
	if hyphenate then s = s:gsub("%s", "-") end
	if capitalize then s = s:gsub("^%l", string.upper) end
	return s
end

local p = {  -- functions that can be called from another module
	roman_to_numeral = roman_to_numeral,
	spell_number = _numeral_to_swedish,
}

function p.numeral_to_swedish(frame)
	local args = frame.args
	local num = args[1]
	num = num:gsub("^%s*(.-)%s*$", "%1")   -- Trim whitespace
	num = num:gsub(",", "")   -- Remove commas
	if num ~= '' then  -- a fraction may have an empty whole number
		if not num:find("^%-?%d*%.?%d*%-?[Ee]?[+%-]?%d*$") then
			-- Input not in a valid format, try to pass it through #expr to see
			-- if that produces a number (e.g. "3 + 5" will become "8").
			num = frame:preprocess('{{#expr: ' .. num .. '}}')
		end
	end

	-- Pass args from frame to helper function
	return _numeral_to_swedish(
		num,
		args['numerator'],
		args['denominator'],
		args['case'] == 'U' or args['case'] == 'u',
		args['sp'] ~= 'us',
		args['adj'] == 'on',
		args['ord'] == 'on',
		args['pl'] == 'on',
		args['lk'],
		args['minus'],
		args['round'],
		args['zero'],
		args['one'] == 'one'  -- experiment: using '|one=one' makes fraction 2+1/2 give "two and one-half" instead of "two and a half"
	) or ''
end

---- recursive function for p.decToHex
local function decToHexDigit(dec)
	local dig = {"0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F"}
	local div = math.floor(dec/16)
	local mod = dec-(16*div)
	if div >= 1 then return decToHexDigit(div)..dig[mod+1] else return dig[mod+1] end
end -- I think this is supposed to be done with a tail call but first I want something that works at all
---- finds all the decimal numbers in the input text and hexes each of them
function p.decToHex(frame)
	local args=frame.args
	local parent=frame.getParent(frame)
	local pargs={}
	if parent then pargs=parent.args end
	local text=args[1] or pargs[1] or ""
	local minlength=args.minlength or pargs.minlength or 1
	minlength=tonumber(minlength)
	local prowl=mw.ustring.gmatch(text,"(.-)(%d+)")
	local output=""
	repeat
		local chaff,dec=prowl()
		if not(dec) then break end
		local hex=decToHexDigit(dec)
		while (mw.ustring.len(hex)<minlength) do hex="0"..hex end
		output=output..chaff..hex
	until false
	local chaff=mw.ustring.match(text,"(%D+)$") or ""
	return output..chaff
end

return p