Anda dapat membuat halaman dokumentasi untuk buat pada modul Scribunto ini.
Penyunting dapat melakukan uji coba pada halaman bak pasir (buat | cermin) dan kasus uji (buat) modul ini.
Subhalaman modul ini.
Penyunting dapat melakukan uji coba pada halaman bak pasir (buat | cermin) dan kasus uji (buat) modul ini.
Subhalaman modul ini.
-- Module for converting between different representations of numbers. See talk page for user documentation. -- For unit tests see: [[Modul:ConvertNumeric/testcases]] -- When editing, preview with: [[Pembicaraan Modul:ConvertNumeric/testcases]] -- First, edit [[Modul:ConvertNumeric/sandbox]], then preview with [[Pembicaraan Modul:ConvertNumeric/sandbox/testcases]] require('strict') localones_position={ [0]='nol', [1]='satu', [2]='dua', [3]='tiga', [4]='empat', [5]='lima', [6]='enam', [7]='tujuh', [8]='delapan', [9]='sembilan', } localnumbers_position={ [1]='se', [2]='dua ', [3]='tiga ', [4]='empat ', [5]='lima ', [6]='enam ', [7]='tujuh ', [8]='delapan ', [9]='sembilan ', } localgroups={ [1]='ribu', [2]='juta', [3]='miliar', [4]='triliun', [5]='kuadriliun', [6]='kuintiliun', [7]='sekstiliun', [8]='septiliun', [9]='oktiliun', [10]='noniliun', [11]='desiliun', [12]='undesiliun', [13]='duodesiliun', [14]='tredesiliun', [15]='kuatuordesiliun', [16]='kuindesiliun', [17]='seksdesiliun', [18]='septendesiliun', [19]='oktodesiliun', [20]='novemdesiliun', [21]='vigintiliun', [22]='unvigintiliun', [23]='duovigintiliun', [24]='tresvigintiliun', [25]='kuatuorvigintiliun', [26]='kuinkuavigintiliun', [27]='sesvigintiliun', [28]='septemvigintiliun', [29]='oktovigintiliun', [30]='novemvigintiliun', [31]='trigintiliun', [32]='untrigintiliun', [33]='duotrigintiliun', [34]='trestrigintiliun', [35]='kuatuortrigintiliun', [36]='kuinkuatrigintiliun', [37]='sestrigintiliun', [38]='septentrigintiliun', [39]='oktotrigintiliun', [40]='noventrigintiliun', [41]='kuadragintiliun', [51]='kuinkuagintiliun', [61]='seksagintiliun', [71]='septuagintiliun', [81]='oktogintiliun', [91]='nonagintiliun', [101]='sentiliun', [102]='unsentiliun', [103]='duosentiliun', [104]='tresentiliun', [111]='desisentiliun', [112]='undesisentiliun', [121]='vigintisentiliun', [122]='unvigintisentiliun', [131]='trigintasentiliun', [141]='kuadragintasentiliun', [151]='kuinkuagintasentiliun', [161]='seksagintasentiliun', [171]='septuagintasentiliun', [181]='oktogintasentiliun', [191]='nonagintasentiliun', [201]='dusentiliun', [301]='tresentiliun', [401]='kuadringentiliun', [501]='kuingentiliun', [601]='sesentiliun', [701]='septingentiliun', [801]='oktingentiliun', [901]='nongentiliun', [1001]='miliniliun', } localroman_numerals={ I=1, V=5, X=10, L=50, C=100, D=500, M=1000 } localones_position_ord={ [0]='ke-nol', [1]='kesatu', [2]='kedua', [3]='ketiga', [4]='keempat', [5]='kelima', [6]='keenam', [7]='ketujuh', [8]='kedelapan', [9]='kesembilan', [10]='kesepuluh', [11]='kesebelas', [12]='kedua belas', [13]='ketiga belas', [14]='keempat belas', [15]='kelima belas', [16]='keenam belas', [17]='ketujuh belas', [18]='kedelapan belas', [19]='kesembilan belas' } localindord_tens_end={ ['kedua puluh']=20, ['ketiga puluh']=30, ['keempat puluh']=40, ['kelima puluh']=50, ['keenam puluh']=60, ['ketujuh puluh']=70, ['kedelapan puluh']=80, ['kesembilan puluh']=90, } localind_tens_cont={ ['dua puluh']=20, ['tiga puluh']=30, ['empat puluh']=40, ['lima puluh']=50, ['enam puluh']=60, ['tujuh puluh']=70, ['delapan puluh']=80, ['sembilan puluh']=90, } -- Mengubah suatu angka Romawi valid (atau beberapa yang invalid) menjadi suatu angka. Memberikan -1, errorstring kalau error localfunctionroman_to_numeral(roman) iftype(roman)~="string"thenreturn-1,"masukan angka Romawi bukanlah suatu string"end localrev=roman:reverse() localraising=true locallast=0 localresult=0 fori=1,#revdo localc=rev:sub(i,i) localnext=roman_numerals[c] ifnext==nilthenreturn-1,"angka Romawi mengandung karakter yang tidak mendukung"..cend ifnext>lastthen result=result+next raising=true elseifnext<lastthen result=result-next raising=false elseifraisingthen result=result+next else result=result-next end last=next end returnresult end -- Mengubah suatu bilangan bulat antara 0 dan 100 ke dalam bahasa Indonesia (misalnya 47 -> empat puluh tujuh) localfunctionnumeral_to_indonesian_less_100(num,zero) ifnum==0andzero~=nilthen returnzero elseifnum<10then returnones_position[num] elseifnum%10==0then returnnumbers_position[num/10]..'puluh' elseifmath.floor(num/10)==1andnum~=10then returnnumbers_position[num%10]..'belas' else returnnumbers_position[math.floor(num/10)]..'puluh '..ones_position[num%10] end end localfunctionstandard_suffix(ordinal,plural) ifordinalthenreturn'ke'end ifpluralthenreturn'an'end return'' end -- Mengubah suatu bilangan bulat (dalam bentuk kata-kata) antara 0 dan 1000 ke dalam bahasa Indonesia (misalnya 47 -> empat puluh tujuh) localfunctionnumeral_to_indonesian_less_1000(num,zero) num=tonumber(num) ifnum<100then returnnumeral_to_indonesian_less_100(num,zero) elseifnum%100==0then returnnumbers_position[num/100]..'ratus' else returnnumbers_position[math.floor(num/100)]..'ratus '..numeral_to_indonesian_less_100(num%100,zero) end end --------------- NOT WORKING PROPERLY, STARTS HERE ---------------- -- Converts an ordinal in indonesian text from 'zeroth' to 'ninety-ninth' inclusive to a number [0–99], else -1. localfunctionindonesian_to_ordinal(indonesian) localind=string.lower(indonesianor'') localindord_lt20={}-- ones_position_ord{} keys & values swapped fork,vinpairs(ones_position_ord)do indord_lt20[v]=k end ifindord_lt20[ind]then returnindord_lt20[ind]-- e.g. first -> 1 elseifindord_tens_end[ind]then returnindord_tens_end[ind]-- e.g. ninetieth -> 90 else localtens,ones=string.match(ind,'^([a-z]+)[%s%-]+([a-z]+)$') iftensandonesthen localtens_cont=ind_tens_cont[tens] localones_end=indord_lt20[ones] iftens_contandones_endthen returntens_cont+ones_end-- e.g. ninety-ninth -> 99 end end end return-1-- Failed end -- Mengubah angka ke dalam bahasa Indonesia mulai 'nol' hingga 'sembilan puluh sembilan' [0–99], selain itu -1. localfunctionindonesian_to_numeral(indonesian) localind=string.lower(indonesianor'') localind_lt20={['single']=1}-- ones_position{} keys & values swapped fork,vinpairs(ones_position)do ind_lt20[v]=k end ifind_lt20[ind]then returnind_lt20[ind]-- e.g. one -> 1 elseifind_tens_cont[ind]then returnind_tens_cont[ind]-- e.g. ninety -> 90 else localtens,ones=string.match(ind,'^([a-z]+)[%s%-]+([a-z]+)$') iftensandonesthen localtens_cont=ind_tens_cont[tens] localones_end=ind_lt20[ones] iftens_contandones_endthen returntens_cont+ones_end-- e.g. ninety-nine -> 99 end end end return-1-- Failed end --------------- NOT WORKING PROPERLY, ENDS HERE ---------------- -- Converts a number expressed as a string in scientific notation to a string in standard decimal notation -- e.g. 1.23E5 -> 123000, 1.23E-5 = .0000123. Conversion is exact, no rounding is performed. localfunctionscientific_notation_to_decimal(num) localexponent,subs=num:gsub("^%-?%d*%.?%d*%-?[Ee]([+%-]?%d+)$","%1") ifsubs==0thenreturnnumend-- Input bukan dalam notasi ilmiah, tidak ada perubahan exponent=tonumber(exponent) localnegative=num:find("^%-") local_,decimal_pos=num:find("%.") -- Mantissa will consist of all decimal digits with no decimal point localmantissa=num:gsub("^%-?(%d*)%.?(%d*)%-?[Ee][+%-]?%d+$","%1%2") ifnegativeanddecimal_posthendecimal_pos=decimal_pos-1end ifnotdecimal_posthendecimal_pos=#mantissa+1end -- Remove leading zeros unless decimal point is in first position whiledecimal_pos>1andmantissa:sub(1,1)=='0'do mantissa=mantissa:sub(2) decimal_pos=decimal_pos-1 end -- Shift decimal point right for exponent > 0 whileexponent>0do decimal_pos=decimal_pos+1 exponent=exponent-1 ifdecimal_pos>#mantissa+1thenmantissa=mantissa..'0'end -- Remove leading zeros unless decimal point is in first position whiledecimal_pos>1andmantissa:sub(1,1)=='0'do mantissa=mantissa:sub(2) decimal_pos=decimal_pos-1 end end -- Shift decimal point left for exponent < 0 whileexponent<0do ifdecimal_pos==1then mantissa='0'..mantissa else decimal_pos=decimal_pos-1 end exponent=exponent+1 end -- Insert decimal point in correct position and return return(negativeand'-'or'')..mantissa:sub(1,decimal_pos-1)..'.'..mantissa:sub(decimal_pos) end -- Rounds a number to the nearest integer (NOT USED) localfunctionround_num(x) ifx%1>=0.5then returnmath.ceil(x) else returnmath.floor(x) end end -- Rounds a number to the nearest two-word number (round = up, down, or "on" for round to nearest). -- Numbers with two digits before the decimal will be rounded to an integer as specified by round. -- Larger numbers will be rounded to a number with only one nonzero digit in front and all other digits zero. -- Negative sign is preserved and does not count towards word limit. localfunctionround_for_indonesian(num,round) -- If an integer with at most two digits, just return ifnum:find("^%-?%d?%d%.?$")thenreturnnumend localnegative=num:find("^%-") ifnegativethen -- We're rounding magnitude so flip it ifround=='up'thenround='down'elseifround=='down'thenround='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*)$") ifsmall_intthen ifsmall_int==''thensmall_int='0'end if(round=='up'andtrailing_digits:find('[1-9]'))or(round=='on'andtonumber(round_digit)>=5)then small_int=tostring(tonumber(small_int)+1) end return(negativeand'-'or'')..small_int end -- When rounding up, any number with > 1 nonzero digit will round up (e.g. 1000000.001 rounds up to 2000000) localnonzero_digits=0 fordigitinnum: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*)$") iftonumber(lead_digit..round_digit)<20and(1+#rest)%3==0then -- In indonesian 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'andnonzero_digits>1)or(round=='on'andtonumber(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(negativeand'-'or'')..lead_digit..'0'..rest end localdenominators={ [2]={'perdua'}, [3]={'pertiga'}, [4]={'perempat'}, [5]={'perlima'}, [6]={'perenam'}, [8]={'pertujuh'}, [9]={'persembilan'}, [10]={'persepuluh'}, [16]={'perenambelas'}, } -- 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 indonesian 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 negative. -- 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 -- negative_word (string): word to use for negative sign, if whole is empty -- use_one (boolean): false: 2+1/2 → "two and a half"; true: "two and one-half" localfunctionfraction_to_indonesian(whole,numerator,denominator,sp_us,negative_word,use_one) ifnumeratorordenominatorthen localfinished=(whole==nilorwhole=='') localsign='' ifnumeratorthen iffinishedandnumerator:sub(1,1)=='-'then numerator=numerator:sub(2) sign=negative_word..' ' end else numerator='1' end ifnotnumerator:match('^%d+$')ornotdenominatorornotdenominator:match('^%d+$')then return'unsupported','' end numerator=tonumber(numerator) denominator=tonumber(denominator) localdendata=denominators[denominator] ifnot(dendataand1<=numeratorandnumerator<=99)then return'unsupported','' end localnumstr,denstr localsep='-' ifnumerator==1then denstr=sp_usanddendata.usordendata[1] iffinishedoruse_onethen numstr='one' elseifdenstr:match('^[aeiou]')then numstr='an' sep=' ' else numstr='a' sep=' ' end else numstr=numeral_to_indonesian_less_100(numerator) denstr=dendata.plural ifnotdenstrthen denstr=(sp_usanddendata.usordendata[1])..'s' end end iffinishedthen return'finished',sign..numstr..sep..denstr end return'ok',' and '..numstr..sep..denstr end return'ok','' end -- Takes a decimal number and converts it to indonesian 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 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") -- negative_word: word to use for negative sign (typically 'negative' 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" localfunction_numeral_to_indonesian(num,numerator,denominator,capitalize,hyphenate,ordinal,plural,links,negative_word,round,zero,use_one) ifnotnegative_wordthen negative_word='minus' end localstatus,fraction_text=fraction_to_indonesian(num,numerator,denominator,negative_word,use_one) ifstatus=='unsupported'then returnnil end ifstatus=='finished'then -- Input is a fraction with no whole number. -- Hack to avoid executing stuff that depends on num being a number. locals=fraction_text ifhyphenatethens=s:gsub("%s","-")end ifcapitalizethens=s:gsub("^%l",string.upper)end returns end num=scientific_notation_to_decimal(num) ifroundandround~=''then ifround~='on'andround~='up'andround~='down'then error("Invalid rounding mode") end num=round_for_indonesian(num,round) end -- Separate into negative sign, num (digits before decimal), decimal_places (digits after decimal) localMINUS='−'-- Unicode U+2212 MINUS SIGN (may be in values from [[Module:Convert]]) ifnum:sub(1,#MINUS)==MINUSthen num='-'..num:sub(#MINUS+1)-- replace MINUS with '-' elseifnum:sub(1,1)=='+'then num=num:sub(2)-- ignore any '+' end localnegative=num:find("^%-") localdecimal_places,subs=num:gsub("^%-?%d*%.(%d+)$","%1") ifsubs==0thendecimal_places=nilend num,subs=num:gsub("^%-?(%d*)%.?%d*$","%1") ifnum==''anddecimal_placesthennum='0'end ifsubs==0ornum==''thenerror("Invalid decimal numeral")end -- For each group of 3 digits except the last one, print with appropriate group name (e.g. million) locals='' while#num>3do ifs~=''thens=s..' 'end localgroup_num=math.floor((#num-1)/3) localgroup=groups[group_num] localgroup_digits=#num-group_num*3 ifgroup_num==1andnum:sub(1,group_digits)=='1'then s=s..'se' else s=s..numeral_to_indonesian_less_1000(num:sub(1,group_digits),false,false,false,zero)..' ' end iflinksand(((links=='on'andgroup_num>=3)orlinks:find(group))andgroup_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 ifs~=''andnum~=''then s=s..' ' end ifs==''ornum~=''then s=s..numeral_to_indonesian_less_1000(num,zero) elseifpluralthen -- Round numbers like "one million" take standard suffixes for ordinal/plural s=s..standard_suffix(ordinal,plural) elseifordinalthen s=standard_suffix(ordinal,plural)..s end -- For decimal places (if any) output "point" followed by spelling out digit by digit ifdecimal_placesthen s=s..' koma' fori=1,#decimal_placesdo s=s..' '..ones_position[tonumber(decimal_places:sub(i,i))] end end s=s:gsub("^%s*(.-)%s*$","%1")-- Trim whitespace ifordinalandpluralthens=s..'s'end-- s suffix works for all ordinals ifnegativeands~=zerothens=negative_word..' '..send s=s:gsub("negative zero","zero") s=s..fraction_text ifhyphenatethens=s:gsub("%s","-")end ifcapitalizethens=s:gsub("^%l",string.upper)end returns end localfunction_numeral_to_indonesian2(args) localnum=tostring(args.num) num=num:gsub("^%s*(.-)%s*$","%1")-- Trim whitespace num=num:gsub(",","")-- Remove commas num=num:gsub("^<span[^<>]*></span>","")-- Generated by Template:age ifnum~=''then-- a fraction may have an empty whole number ifnotnum:find("^%-?%d*%.?%d*%-?[Ee]?[+%-]?%d*$")then -- Input not in a valid format, try to eval it as an expr to see -- if that produces a number (e.g. "3 + 5" will become "8"). localnoerr,result=pcall(mw.ext.ParserFunctions.expr,num) ifnoerrthen num=result end end end -- Pass args from frame to helper function return_numeral_to_indonesian( num, args['numerator'], args['denominator'], args['capitalize'], args['use_and'], args['hyphenate'], args['ordinal'], args['plural'], args['links'], args['negative_word'], args['round'], args['zero'], args['use_one'] )or'' end localp={-- Functions that can be called from another module roman_to_numeral=roman_to_numeral, spell_number=_numeral_to_indonesian, spell_number2=_numeral_to_indonesian2, indonesian_to_ordinal=indonesian_to_ordinal, indonesian_to_numeral=indonesian_to_numeral, } functionp._roman_to_numeral(frame)-- Callable via {{#invoke:ConvertNumeric|_roman_to_numeral|VI}} returnroman_to_numeral(frame.args[1]) end functionp._indonesian_to_ordinal(frame)-- callable via {{#invoke:ConvertNumeric|_indonesian_to_ordinal|First}} returnindonesian_to_ordinal(frame.args[1]) end functionp._indonesian_to_numeral(frame)-- callable via {{#invoke:ConvertNumeric|_indonesian_to_numeral|One}} returnindonesian_to_numeral(frame.args[1]) end functionp.numeral_to_indonesian(frame) localargs=frame.args -- Tail call to helper function passing args from frame return_numeral_to_indonesian2{ ['num']=args[1], ['numerator']=args['numerator'], ['denominator']=args['denominator'], ['capitalize']=args['case']=='U'orargs['case']=='u', ['hyphenate']=args['adj']=='on', ['ordinal']=args['ord']=='on', ['plural']=args['pl']=='on', ['links']=args['lk'], ['negative_word']=args['negative'], ['round']=args['round'], ['zero']=args['zero'], ['use_one']=args['one']=='one'-- experiment: using '|one=one' makes fraction 2+1/2 give "two and one-half" instead of "two and a half" } end ---- recursive function for p.decToHex localfunctiondecToHexDigit(dec) localdig={"0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F"} localdiv=math.floor(dec/16) localmod=dec-(16*div) ifdiv>=1thenreturndecToHexDigit(div)..dig[mod+1]elsereturndig[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 functionp.decToHex(frame) localargs=frame.args localparent=frame.getParent(frame) localpargs={} ifparentthenpargs=parent.argsend localtext=args[1]orpargs[1]or"" localminlength=args.minlengthorpargs.minlengthor1 minlength=tonumber(minlength) localprowl=mw.ustring.gmatch(text,"(.-)(%d+)") localoutput="" repeat localchaff,dec=prowl() ifnot(dec)thenbreakend localhex=decToHexDigit(dec) while(mw.ustring.len(hex)<minlength)dohex="0"..hexend output=output..chaff..hex untilfalse localchaff=mw.ustring.match(text,"(%D+)$")or"" returnoutput..chaff end returnp