calc.go 93 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471
  1. // Copyright 2016 - 2020 The excelize Authors. All rights reserved. Use of
  2. // this source code is governed by a BSD-style license that can be found in
  3. // the LICENSE file.
  4. //
  5. // Package excelize providing a set of functions that allow you to write to
  6. // and read from XLSX / XLSM / XLTM files. Supports reading and writing
  7. // spreadsheet documents generated by Microsoft Exce™ 2007 and later. Supports
  8. // complex components by high compatibility, and provided streaming API for
  9. // generating or reading data from a worksheet with huge amounts of data. This
  10. // library needs Go version 1.10 or later.
  11. package excelize
  12. import (
  13. "bytes"
  14. "container/list"
  15. "errors"
  16. "fmt"
  17. "math"
  18. "math/rand"
  19. "reflect"
  20. "regexp"
  21. "sort"
  22. "strconv"
  23. "strings"
  24. "time"
  25. "unicode"
  26. "github.com/xuri/efp"
  27. )
  28. // Excel formula errors
  29. const (
  30. formulaErrorDIV = "#DIV/0!"
  31. formulaErrorNAME = "#NAME?"
  32. formulaErrorNA = "#N/A"
  33. formulaErrorNUM = "#NUM!"
  34. formulaErrorVALUE = "#VALUE!"
  35. formulaErrorREF = "#REF!"
  36. formulaErrorNULL = "#NULL"
  37. formulaErrorSPILL = "#SPILL!"
  38. formulaErrorCALC = "#CALC!"
  39. formulaErrorGETTINGDATA = "#GETTING_DATA"
  40. )
  41. // Numeric precision correct numeric values as legacy Excel application
  42. // https://en.wikipedia.org/wiki/Numeric_precision_in_Microsoft_Excel In the
  43. // top figure the fraction 1/9000 in Excel is displayed. Although this number
  44. // has a decimal representation that is an infinite string of ones, Excel
  45. // displays only the leading 15 figures. In the second line, the number one
  46. // is added to the fraction, and again Excel displays only 15 figures.
  47. const numericPrecision = 1000000000000000
  48. // cellRef defines the structure of a cell reference.
  49. type cellRef struct {
  50. Col int
  51. Row int
  52. Sheet string
  53. }
  54. // cellRef defines the structure of a cell range.
  55. type cellRange struct {
  56. From cellRef
  57. To cellRef
  58. }
  59. // formula criteria condition enumeration.
  60. const (
  61. _ byte = iota
  62. criteriaEq
  63. criteriaLe
  64. criteriaGe
  65. criteriaL
  66. criteriaG
  67. criteriaBeg
  68. criteriaEnd
  69. )
  70. // formulaCriteria defined formula criteria parser result.
  71. type formulaCriteria struct {
  72. Type byte
  73. Condition string
  74. }
  75. // ArgType is the type if formula argument type.
  76. type ArgType byte
  77. // Formula argument types enumeration.
  78. const (
  79. ArgUnknown ArgType = iota
  80. ArgString
  81. ArgMatrix
  82. )
  83. // formulaArg is the argument of a formula or function.
  84. type formulaArg struct {
  85. String string
  86. Matrix [][]formulaArg
  87. Type ArgType
  88. }
  89. // formulaFuncs is the type of the formula functions.
  90. type formulaFuncs struct{}
  91. // tokenPriority defined basic arithmetic operator priority.
  92. var tokenPriority = map[string]int{
  93. "^": 5,
  94. "*": 4,
  95. "/": 4,
  96. "+": 3,
  97. "-": 3,
  98. "=": 2,
  99. "<": 2,
  100. "<=": 2,
  101. ">": 2,
  102. ">=": 2,
  103. "&": 1,
  104. }
  105. // CalcCellValue provides a function to get calculated cell value. This
  106. // feature is currently in working processing. Array formula, table formula
  107. // and some other formulas are not supported currently.
  108. //
  109. // Supported formulas:
  110. //
  111. // ABS, ACOS, ACOSH, ACOT, ACOTH, AND, ARABIC, ASIN, ASINH, ATAN2, ATANH,
  112. // BASE, CEILING, CEILING.MATH, CEILING.PRECISE, CLEAN, COMBIN, COMBINA,
  113. // COS, COSH, COT, COTH, COUNTA, CSC, CSCH, DATE, DECIMAL, DEGREES, EVEN,
  114. // EXP, FACT, FACTDOUBLE, FLOOR, FLOOR.MATH, FLOOR.PRECISE, GCD, INT,
  115. // ISBLANK, ISERR, ISERROR, ISEVEN, ISNA, ISNONTEXT, ISNUMBER, ISO.CEILING,
  116. // ISODD, LCM, LN, LOG, LOG10, LOWER, MDETERM, MEDIAN, MOD, MROUND,
  117. // MULTINOMIAL, MUNIT, NA, ODD, OR, PI, POWER, PRODUCT, PROPER, QUOTIENT,
  118. // RADIANS, RAND, RANDBETWEEN, ROUND, ROUNDDOWN, ROUNDUP, SEC, SECH, SIGN,
  119. // SIN, SINH, SQRT, SQRTPI, SUM, SUMIF, SUMSQ, TAN, TANH, TRIM, TRUNC,
  120. // UPPER
  121. //
  122. func (f *File) CalcCellValue(sheet, cell string) (result string, err error) {
  123. var (
  124. formula string
  125. token efp.Token
  126. )
  127. if formula, err = f.GetCellFormula(sheet, cell); err != nil {
  128. return
  129. }
  130. ps := efp.ExcelParser()
  131. tokens := ps.Parse(formula)
  132. if tokens == nil {
  133. return
  134. }
  135. if token, err = f.evalInfixExp(sheet, tokens); err != nil {
  136. return
  137. }
  138. result = token.TValue
  139. if len(result) > 16 {
  140. num, e := roundPrecision(result)
  141. if e != nil {
  142. return result, err
  143. }
  144. result = strings.ToUpper(num)
  145. }
  146. return
  147. }
  148. // getPriority calculate arithmetic operator priority.
  149. func getPriority(token efp.Token) (pri int) {
  150. pri, _ = tokenPriority[token.TValue]
  151. if token.TValue == "-" && token.TType == efp.TokenTypeOperatorPrefix {
  152. pri = 6
  153. }
  154. if token.TSubType == efp.TokenSubTypeStart && token.TType == efp.TokenTypeSubexpression { // (
  155. pri = 0
  156. }
  157. return
  158. }
  159. // evalInfixExp evaluate syntax analysis by given infix expression after
  160. // lexical analysis. Evaluate an infix expression containing formulas by
  161. // stacks:
  162. //
  163. // opd - Operand
  164. // opt - Operator
  165. // opf - Operation formula
  166. // opfd - Operand of the operation formula
  167. // opft - Operator of the operation formula
  168. //
  169. // Evaluate arguments of the operation formula by list:
  170. //
  171. // args - Arguments of the operation formula
  172. //
  173. // TODO: handle subtypes: Nothing, Text, Logical, Error, Concatenation, Intersection, Union
  174. //
  175. func (f *File) evalInfixExp(sheet string, tokens []efp.Token) (efp.Token, error) {
  176. var err error
  177. opdStack, optStack, opfStack, opfdStack, opftStack := NewStack(), NewStack(), NewStack(), NewStack(), NewStack()
  178. argsList := list.New()
  179. for i := 0; i < len(tokens); i++ {
  180. token := tokens[i]
  181. // out of function stack
  182. if opfStack.Len() == 0 {
  183. if err = f.parseToken(sheet, token, opdStack, optStack); err != nil {
  184. return efp.Token{}, err
  185. }
  186. }
  187. // function start
  188. if token.TType == efp.TokenTypeFunction && token.TSubType == efp.TokenSubTypeStart {
  189. opfStack.Push(token)
  190. continue
  191. }
  192. // in function stack, walk 2 token at once
  193. if opfStack.Len() > 0 {
  194. var nextToken efp.Token
  195. if i+1 < len(tokens) {
  196. nextToken = tokens[i+1]
  197. }
  198. // current token is args or range, skip next token, order required: parse reference first
  199. if token.TSubType == efp.TokenSubTypeRange {
  200. if !opftStack.Empty() {
  201. // parse reference: must reference at here
  202. result, err := f.parseReference(sheet, token.TValue)
  203. if err != nil {
  204. return efp.Token{TValue: formulaErrorNAME}, err
  205. }
  206. if result.Type != ArgString {
  207. return efp.Token{}, errors.New(formulaErrorVALUE)
  208. }
  209. opfdStack.Push(efp.Token{
  210. TType: efp.TokenTypeOperand,
  211. TSubType: efp.TokenSubTypeNumber,
  212. TValue: result.String,
  213. })
  214. continue
  215. }
  216. if nextToken.TType == efp.TokenTypeArgument || nextToken.TType == efp.TokenTypeFunction {
  217. // parse reference: reference or range at here
  218. result, err := f.parseReference(sheet, token.TValue)
  219. if err != nil {
  220. return efp.Token{TValue: formulaErrorNAME}, err
  221. }
  222. if result.Type == ArgUnknown {
  223. return efp.Token{}, errors.New(formulaErrorVALUE)
  224. }
  225. argsList.PushBack(result)
  226. continue
  227. }
  228. }
  229. // check current token is opft
  230. if err = f.parseToken(sheet, token, opfdStack, opftStack); err != nil {
  231. return efp.Token{}, err
  232. }
  233. // current token is arg
  234. if token.TType == efp.TokenTypeArgument {
  235. for !opftStack.Empty() {
  236. // calculate trigger
  237. topOpt := opftStack.Peek().(efp.Token)
  238. if err := calculate(opfdStack, topOpt); err != nil {
  239. return efp.Token{}, err
  240. }
  241. opftStack.Pop()
  242. }
  243. if !opfdStack.Empty() {
  244. argsList.PushBack(formulaArg{
  245. String: opfdStack.Pop().(efp.Token).TValue,
  246. Type: ArgString,
  247. })
  248. }
  249. continue
  250. }
  251. // current token is logical
  252. if token.TType == efp.OperatorsInfix && token.TSubType == efp.TokenSubTypeLogical {
  253. }
  254. // current token is text
  255. if token.TType == efp.TokenTypeOperand && token.TSubType == efp.TokenSubTypeText {
  256. argsList.PushBack(formulaArg{
  257. String: token.TValue,
  258. Type: ArgString,
  259. })
  260. }
  261. // current token is function stop
  262. if token.TType == efp.TokenTypeFunction && token.TSubType == efp.TokenSubTypeStop {
  263. for !opftStack.Empty() {
  264. // calculate trigger
  265. topOpt := opftStack.Peek().(efp.Token)
  266. if err := calculate(opfdStack, topOpt); err != nil {
  267. return efp.Token{}, err
  268. }
  269. opftStack.Pop()
  270. }
  271. // push opfd to args
  272. if opfdStack.Len() > 0 {
  273. argsList.PushBack(formulaArg{
  274. String: opfdStack.Pop().(efp.Token).TValue,
  275. Type: ArgString,
  276. })
  277. }
  278. // call formula function to evaluate
  279. result, err := callFuncByName(&formulaFuncs{}, strings.NewReplacer(
  280. "_xlfn", "", ".", "").Replace(opfStack.Peek().(efp.Token).TValue),
  281. []reflect.Value{reflect.ValueOf(argsList)})
  282. if err != nil {
  283. return efp.Token{}, err
  284. }
  285. argsList.Init()
  286. opfStack.Pop()
  287. if opfStack.Len() > 0 { // still in function stack
  288. opfdStack.Push(efp.Token{TValue: result, TType: efp.TokenTypeOperand, TSubType: efp.TokenSubTypeNumber})
  289. } else {
  290. opdStack.Push(efp.Token{TValue: result, TType: efp.TokenTypeOperand, TSubType: efp.TokenSubTypeNumber})
  291. }
  292. }
  293. }
  294. }
  295. for optStack.Len() != 0 {
  296. topOpt := optStack.Peek().(efp.Token)
  297. if err = calculate(opdStack, topOpt); err != nil {
  298. return efp.Token{}, err
  299. }
  300. optStack.Pop()
  301. }
  302. if opdStack.Len() == 0 {
  303. return efp.Token{}, errors.New("formula not valid")
  304. }
  305. return opdStack.Peek().(efp.Token), err
  306. }
  307. // calcPow evaluate exponentiation arithmetic operations.
  308. func calcPow(rOpd, lOpd string, opdStack *Stack) error {
  309. lOpdVal, err := strconv.ParseFloat(lOpd, 64)
  310. if err != nil {
  311. return err
  312. }
  313. rOpdVal, err := strconv.ParseFloat(rOpd, 64)
  314. if err != nil {
  315. return err
  316. }
  317. result := math.Pow(lOpdVal, rOpdVal)
  318. opdStack.Push(efp.Token{TValue: fmt.Sprintf("%g", result), TType: efp.TokenTypeOperand, TSubType: efp.TokenSubTypeNumber})
  319. return nil
  320. }
  321. // calcEq evaluate equal arithmetic operations.
  322. func calcEq(rOpd, lOpd string, opdStack *Stack) error {
  323. opdStack.Push(efp.Token{TValue: strings.ToUpper(strconv.FormatBool(rOpd == lOpd)), TType: efp.TokenTypeOperand, TSubType: efp.TokenSubTypeNumber})
  324. return nil
  325. }
  326. // calcL evaluate less than arithmetic operations.
  327. func calcL(rOpd, lOpd string, opdStack *Stack) error {
  328. lOpdVal, err := strconv.ParseFloat(lOpd, 64)
  329. if err != nil {
  330. return err
  331. }
  332. rOpdVal, err := strconv.ParseFloat(rOpd, 64)
  333. if err != nil {
  334. return err
  335. }
  336. opdStack.Push(efp.Token{TValue: strings.ToUpper(strconv.FormatBool(rOpdVal > lOpdVal)), TType: efp.TokenTypeOperand, TSubType: efp.TokenSubTypeNumber})
  337. return nil
  338. }
  339. // calcLe evaluate less than or equal arithmetic operations.
  340. func calcLe(rOpd, lOpd string, opdStack *Stack) error {
  341. lOpdVal, err := strconv.ParseFloat(lOpd, 64)
  342. if err != nil {
  343. return err
  344. }
  345. rOpdVal, err := strconv.ParseFloat(rOpd, 64)
  346. if err != nil {
  347. return err
  348. }
  349. opdStack.Push(efp.Token{TValue: strings.ToUpper(strconv.FormatBool(rOpdVal >= lOpdVal)), TType: efp.TokenTypeOperand, TSubType: efp.TokenSubTypeNumber})
  350. return nil
  351. }
  352. // calcG evaluate greater than or equal arithmetic operations.
  353. func calcG(rOpd, lOpd string, opdStack *Stack) error {
  354. lOpdVal, err := strconv.ParseFloat(lOpd, 64)
  355. if err != nil {
  356. return err
  357. }
  358. rOpdVal, err := strconv.ParseFloat(rOpd, 64)
  359. if err != nil {
  360. return err
  361. }
  362. opdStack.Push(efp.Token{TValue: strings.ToUpper(strconv.FormatBool(rOpdVal < lOpdVal)), TType: efp.TokenTypeOperand, TSubType: efp.TokenSubTypeNumber})
  363. return nil
  364. }
  365. // calcGe evaluate greater than or equal arithmetic operations.
  366. func calcGe(rOpd, lOpd string, opdStack *Stack) error {
  367. lOpdVal, err := strconv.ParseFloat(lOpd, 64)
  368. if err != nil {
  369. return err
  370. }
  371. rOpdVal, err := strconv.ParseFloat(rOpd, 64)
  372. if err != nil {
  373. return err
  374. }
  375. opdStack.Push(efp.Token{TValue: strings.ToUpper(strconv.FormatBool(rOpdVal <= lOpdVal)), TType: efp.TokenTypeOperand, TSubType: efp.TokenSubTypeNumber})
  376. return nil
  377. }
  378. // calcSplice evaluate splice '&' operations.
  379. func calcSplice(rOpd, lOpd string, opdStack *Stack) error {
  380. opdStack.Push(efp.Token{TValue: lOpd + rOpd, TType: efp.TokenTypeOperand, TSubType: efp.TokenSubTypeNumber})
  381. return nil
  382. }
  383. // calcAdd evaluate addition arithmetic operations.
  384. func calcAdd(rOpd, lOpd string, opdStack *Stack) error {
  385. lOpdVal, err := strconv.ParseFloat(lOpd, 64)
  386. if err != nil {
  387. return err
  388. }
  389. rOpdVal, err := strconv.ParseFloat(rOpd, 64)
  390. if err != nil {
  391. return err
  392. }
  393. result := lOpdVal + rOpdVal
  394. opdStack.Push(efp.Token{TValue: fmt.Sprintf("%g", result), TType: efp.TokenTypeOperand, TSubType: efp.TokenSubTypeNumber})
  395. return nil
  396. }
  397. // calcSubtract evaluate subtraction arithmetic operations.
  398. func calcSubtract(rOpd, lOpd string, opdStack *Stack) error {
  399. lOpdVal, err := strconv.ParseFloat(lOpd, 64)
  400. if err != nil {
  401. return err
  402. }
  403. rOpdVal, err := strconv.ParseFloat(rOpd, 64)
  404. if err != nil {
  405. return err
  406. }
  407. result := lOpdVal - rOpdVal
  408. opdStack.Push(efp.Token{TValue: fmt.Sprintf("%g", result), TType: efp.TokenTypeOperand, TSubType: efp.TokenSubTypeNumber})
  409. return nil
  410. }
  411. // calcMultiply evaluate multiplication arithmetic operations.
  412. func calcMultiply(rOpd, lOpd string, opdStack *Stack) error {
  413. lOpdVal, err := strconv.ParseFloat(lOpd, 64)
  414. if err != nil {
  415. return err
  416. }
  417. rOpdVal, err := strconv.ParseFloat(rOpd, 64)
  418. if err != nil {
  419. return err
  420. }
  421. result := lOpdVal * rOpdVal
  422. opdStack.Push(efp.Token{TValue: fmt.Sprintf("%g", result), TType: efp.TokenTypeOperand, TSubType: efp.TokenSubTypeNumber})
  423. return nil
  424. }
  425. // calcDiv evaluate division arithmetic operations.
  426. func calcDiv(rOpd, lOpd string, opdStack *Stack) error {
  427. lOpdVal, err := strconv.ParseFloat(lOpd, 64)
  428. if err != nil {
  429. return err
  430. }
  431. rOpdVal, err := strconv.ParseFloat(rOpd, 64)
  432. if err != nil {
  433. return err
  434. }
  435. result := lOpdVal / rOpdVal
  436. if rOpdVal == 0 {
  437. return errors.New(formulaErrorDIV)
  438. }
  439. opdStack.Push(efp.Token{TValue: fmt.Sprintf("%g", result), TType: efp.TokenTypeOperand, TSubType: efp.TokenSubTypeNumber})
  440. return nil
  441. }
  442. // calculate evaluate basic arithmetic operations.
  443. func calculate(opdStack *Stack, opt efp.Token) error {
  444. if opt.TValue == "-" && opt.TType == efp.TokenTypeOperatorPrefix {
  445. if opdStack.Len() < 1 {
  446. return errors.New("formula not valid")
  447. }
  448. opd := opdStack.Pop().(efp.Token)
  449. opdVal, err := strconv.ParseFloat(opd.TValue, 64)
  450. if err != nil {
  451. return err
  452. }
  453. result := 0 - opdVal
  454. opdStack.Push(efp.Token{TValue: fmt.Sprintf("%g", result), TType: efp.TokenTypeOperand, TSubType: efp.TokenSubTypeNumber})
  455. }
  456. tokenCalcFunc := map[string]func(rOpd, lOpd string, opdStack *Stack) error{
  457. "^": calcPow,
  458. "*": calcMultiply,
  459. "/": calcDiv,
  460. "+": calcAdd,
  461. "=": calcEq,
  462. "<": calcL,
  463. "<=": calcLe,
  464. ">": calcG,
  465. ">=": calcGe,
  466. "&": calcSplice,
  467. }
  468. if opt.TValue == "-" && opt.TType == efp.TokenTypeOperatorInfix {
  469. if opdStack.Len() < 2 {
  470. return errors.New("formula not valid")
  471. }
  472. rOpd := opdStack.Pop().(efp.Token)
  473. lOpd := opdStack.Pop().(efp.Token)
  474. if err := calcSubtract(rOpd.TValue, lOpd.TValue, opdStack); err != nil {
  475. return err
  476. }
  477. }
  478. fn, ok := tokenCalcFunc[opt.TValue]
  479. if ok {
  480. if opdStack.Len() < 2 {
  481. return errors.New("formula not valid")
  482. }
  483. rOpd := opdStack.Pop().(efp.Token)
  484. lOpd := opdStack.Pop().(efp.Token)
  485. if err := fn(rOpd.TValue, lOpd.TValue, opdStack); err != nil {
  486. return err
  487. }
  488. }
  489. return nil
  490. }
  491. // parseOperatorPrefixToken parse operator prefix token.
  492. func (f *File) parseOperatorPrefixToken(optStack, opdStack *Stack, token efp.Token) (err error) {
  493. if optStack.Len() == 0 {
  494. optStack.Push(token)
  495. } else {
  496. tokenPriority := getPriority(token)
  497. topOpt := optStack.Peek().(efp.Token)
  498. topOptPriority := getPriority(topOpt)
  499. if tokenPriority > topOptPriority {
  500. optStack.Push(token)
  501. } else {
  502. for tokenPriority <= topOptPriority {
  503. optStack.Pop()
  504. if err = calculate(opdStack, topOpt); err != nil {
  505. return
  506. }
  507. if optStack.Len() > 0 {
  508. topOpt = optStack.Peek().(efp.Token)
  509. topOptPriority = getPriority(topOpt)
  510. continue
  511. }
  512. break
  513. }
  514. optStack.Push(token)
  515. }
  516. }
  517. return
  518. }
  519. // isOperatorPrefixToken determine if the token is parse operator prefix
  520. // token.
  521. func isOperatorPrefixToken(token efp.Token) bool {
  522. _, ok := tokenPriority[token.TValue]
  523. if (token.TValue == "-" && token.TType == efp.TokenTypeOperatorPrefix) || ok {
  524. return true
  525. }
  526. return false
  527. }
  528. func (f *File) getDefinedNameRefTo(definedNameName string, currentSheet string) (refTo string) {
  529. for _, definedName := range f.GetDefinedName() {
  530. if definedName.Name == definedNameName {
  531. refTo = definedName.RefersTo
  532. // worksheet scope takes precedence over scope workbook when both definedNames exist
  533. if definedName.Scope == currentSheet {
  534. break
  535. }
  536. }
  537. }
  538. return refTo
  539. }
  540. // parseToken parse basic arithmetic operator priority and evaluate based on
  541. // operators and operands.
  542. func (f *File) parseToken(sheet string, token efp.Token, opdStack, optStack *Stack) error {
  543. // parse reference: must reference at here
  544. if token.TSubType == efp.TokenSubTypeRange {
  545. refTo := f.getDefinedNameRefTo(token.TValue, sheet)
  546. if refTo != "" {
  547. token.TValue = refTo
  548. }
  549. result, err := f.parseReference(sheet, token.TValue)
  550. if err != nil {
  551. return errors.New(formulaErrorNAME)
  552. }
  553. if result.Type != ArgString {
  554. return errors.New(formulaErrorVALUE)
  555. }
  556. token.TValue = result.String
  557. token.TType = efp.TokenTypeOperand
  558. token.TSubType = efp.TokenSubTypeNumber
  559. }
  560. if isOperatorPrefixToken(token) {
  561. if err := f.parseOperatorPrefixToken(optStack, opdStack, token); err != nil {
  562. return err
  563. }
  564. }
  565. if token.TType == efp.TokenTypeSubexpression && token.TSubType == efp.TokenSubTypeStart { // (
  566. optStack.Push(token)
  567. }
  568. if token.TType == efp.TokenTypeSubexpression && token.TSubType == efp.TokenSubTypeStop { // )
  569. for optStack.Peek().(efp.Token).TSubType != efp.TokenSubTypeStart && optStack.Peek().(efp.Token).TType != efp.TokenTypeSubexpression { // != (
  570. topOpt := optStack.Peek().(efp.Token)
  571. if err := calculate(opdStack, topOpt); err != nil {
  572. return err
  573. }
  574. optStack.Pop()
  575. }
  576. optStack.Pop()
  577. }
  578. // opd
  579. if token.TType == efp.TokenTypeOperand && token.TSubType == efp.TokenSubTypeNumber {
  580. opdStack.Push(token)
  581. }
  582. return nil
  583. }
  584. // parseReference parse reference and extract values by given reference
  585. // characters and default sheet name.
  586. func (f *File) parseReference(sheet, reference string) (arg formulaArg, err error) {
  587. reference = strings.Replace(reference, "$", "", -1)
  588. refs, cellRanges, cellRefs := list.New(), list.New(), list.New()
  589. for _, ref := range strings.Split(reference, ":") {
  590. tokens := strings.Split(ref, "!")
  591. cr := cellRef{}
  592. if len(tokens) == 2 { // have a worksheet name
  593. cr.Sheet = tokens[0]
  594. if cr.Col, cr.Row, err = CellNameToCoordinates(tokens[1]); err != nil {
  595. return
  596. }
  597. if refs.Len() > 0 {
  598. e := refs.Back()
  599. cellRefs.PushBack(e.Value.(cellRef))
  600. refs.Remove(e)
  601. }
  602. refs.PushBack(cr)
  603. continue
  604. }
  605. if cr.Col, cr.Row, err = CellNameToCoordinates(tokens[0]); err != nil {
  606. return
  607. }
  608. e := refs.Back()
  609. if e == nil {
  610. cr.Sheet = sheet
  611. refs.PushBack(cr)
  612. continue
  613. }
  614. cellRanges.PushBack(cellRange{
  615. From: e.Value.(cellRef),
  616. To: cr,
  617. })
  618. refs.Remove(e)
  619. }
  620. if refs.Len() > 0 {
  621. e := refs.Back()
  622. cellRefs.PushBack(e.Value.(cellRef))
  623. refs.Remove(e)
  624. }
  625. arg, err = f.rangeResolver(cellRefs, cellRanges)
  626. return
  627. }
  628. // prepareValueRange prepare value range.
  629. func prepareValueRange(cr cellRange, valueRange []int) {
  630. if cr.From.Row < valueRange[0] || valueRange[0] == 0 {
  631. valueRange[0] = cr.From.Row
  632. }
  633. if cr.From.Col < valueRange[2] || valueRange[2] == 0 {
  634. valueRange[2] = cr.From.Col
  635. }
  636. if cr.To.Row > valueRange[1] || valueRange[1] == 0 {
  637. valueRange[1] = cr.To.Row
  638. }
  639. if cr.To.Col > valueRange[3] || valueRange[3] == 0 {
  640. valueRange[3] = cr.To.Col
  641. }
  642. }
  643. // prepareValueRef prepare value reference.
  644. func prepareValueRef(cr cellRef, valueRange []int) {
  645. if cr.Row < valueRange[0] || valueRange[0] == 0 {
  646. valueRange[0] = cr.Row
  647. }
  648. if cr.Col < valueRange[2] || valueRange[2] == 0 {
  649. valueRange[2] = cr.Col
  650. }
  651. if cr.Row > valueRange[1] || valueRange[1] == 0 {
  652. valueRange[1] = cr.Row
  653. }
  654. if cr.Col > valueRange[3] || valueRange[3] == 0 {
  655. valueRange[3] = cr.Col
  656. }
  657. }
  658. // rangeResolver extract value as string from given reference and range list.
  659. // This function will not ignore the empty cell. For example, A1:A2:A2:B3 will
  660. // be reference A1:B3.
  661. func (f *File) rangeResolver(cellRefs, cellRanges *list.List) (arg formulaArg, err error) {
  662. // value range order: from row, to row, from column, to column
  663. valueRange := []int{0, 0, 0, 0}
  664. var sheet string
  665. // prepare value range
  666. for temp := cellRanges.Front(); temp != nil; temp = temp.Next() {
  667. cr := temp.Value.(cellRange)
  668. if cr.From.Sheet != cr.To.Sheet {
  669. err = errors.New(formulaErrorVALUE)
  670. }
  671. rng := []int{cr.From.Col, cr.From.Row, cr.To.Col, cr.To.Row}
  672. sortCoordinates(rng)
  673. cr.From.Col, cr.From.Row, cr.To.Col, cr.To.Row = rng[0], rng[1], rng[2], rng[3]
  674. prepareValueRange(cr, valueRange)
  675. if cr.From.Sheet != "" {
  676. sheet = cr.From.Sheet
  677. }
  678. }
  679. for temp := cellRefs.Front(); temp != nil; temp = temp.Next() {
  680. cr := temp.Value.(cellRef)
  681. if cr.Sheet != "" {
  682. sheet = cr.Sheet
  683. }
  684. prepareValueRef(cr, valueRange)
  685. }
  686. // extract value from ranges
  687. if cellRanges.Len() > 0 {
  688. arg.Type = ArgMatrix
  689. for row := valueRange[0]; row <= valueRange[1]; row++ {
  690. var matrixRow = []formulaArg{}
  691. for col := valueRange[2]; col <= valueRange[3]; col++ {
  692. var cell, value string
  693. if cell, err = CoordinatesToCellName(col, row); err != nil {
  694. return
  695. }
  696. if value, err = f.GetCellValue(sheet, cell); err != nil {
  697. return
  698. }
  699. matrixRow = append(matrixRow, formulaArg{
  700. String: value,
  701. Type: ArgString,
  702. })
  703. }
  704. arg.Matrix = append(arg.Matrix, matrixRow)
  705. }
  706. return
  707. }
  708. // extract value from references
  709. for temp := cellRefs.Front(); temp != nil; temp = temp.Next() {
  710. cr := temp.Value.(cellRef)
  711. var cell string
  712. if cell, err = CoordinatesToCellName(cr.Col, cr.Row); err != nil {
  713. return
  714. }
  715. if arg.String, err = f.GetCellValue(cr.Sheet, cell); err != nil {
  716. return
  717. }
  718. arg.Type = ArgString
  719. }
  720. return
  721. }
  722. // callFuncByName calls the no error or only error return function with
  723. // reflect by given receiver, name and parameters.
  724. func callFuncByName(receiver interface{}, name string, params []reflect.Value) (result string, err error) {
  725. function := reflect.ValueOf(receiver).MethodByName(name)
  726. if function.IsValid() {
  727. rt := function.Call(params)
  728. if len(rt) == 0 {
  729. return
  730. }
  731. if !rt[1].IsNil() {
  732. err = rt[1].Interface().(error)
  733. return
  734. }
  735. result = rt[0].Interface().(string)
  736. return
  737. }
  738. err = fmt.Errorf("not support %s function", name)
  739. return
  740. }
  741. // formulaCriteriaParser parse formula criteria.
  742. func formulaCriteriaParser(exp string) (fc *formulaCriteria) {
  743. fc = &formulaCriteria{}
  744. if exp == "" {
  745. return
  746. }
  747. if match := regexp.MustCompile(`^([0-9]+)$`).FindStringSubmatch(exp); len(match) > 1 {
  748. fc.Type, fc.Condition = criteriaEq, match[1]
  749. return
  750. }
  751. if match := regexp.MustCompile(`^=(.*)$`).FindStringSubmatch(exp); len(match) > 1 {
  752. fc.Type, fc.Condition = criteriaEq, match[1]
  753. return
  754. }
  755. if match := regexp.MustCompile(`^<=(.*)$`).FindStringSubmatch(exp); len(match) > 1 {
  756. fc.Type, fc.Condition = criteriaLe, match[1]
  757. return
  758. }
  759. if match := regexp.MustCompile(`^>=(.*)$`).FindStringSubmatch(exp); len(match) > 1 {
  760. fc.Type, fc.Condition = criteriaGe, match[1]
  761. return
  762. }
  763. if match := regexp.MustCompile(`^<(.*)$`).FindStringSubmatch(exp); len(match) > 1 {
  764. fc.Type, fc.Condition = criteriaL, match[1]
  765. return
  766. }
  767. if match := regexp.MustCompile(`^>(.*)$`).FindStringSubmatch(exp); len(match) > 1 {
  768. fc.Type, fc.Condition = criteriaG, match[1]
  769. return
  770. }
  771. if strings.Contains(exp, "*") {
  772. if strings.HasPrefix(exp, "*") {
  773. fc.Type, fc.Condition = criteriaEnd, strings.TrimPrefix(exp, "*")
  774. }
  775. if strings.HasSuffix(exp, "*") {
  776. fc.Type, fc.Condition = criteriaBeg, strings.TrimSuffix(exp, "*")
  777. }
  778. return
  779. }
  780. fc.Type, fc.Condition = criteriaEq, exp
  781. return
  782. }
  783. // formulaCriteriaEval evaluate formula criteria expression.
  784. func formulaCriteriaEval(val string, criteria *formulaCriteria) (result bool, err error) {
  785. var value, expected float64
  786. var e error
  787. var prepareValue = func(val, cond string) (value float64, expected float64, err error) {
  788. if value, err = strconv.ParseFloat(val, 64); err != nil {
  789. return
  790. }
  791. if expected, err = strconv.ParseFloat(criteria.Condition, 64); err != nil {
  792. return
  793. }
  794. return
  795. }
  796. switch criteria.Type {
  797. case criteriaEq:
  798. return val == criteria.Condition, err
  799. case criteriaLe:
  800. value, expected, e = prepareValue(val, criteria.Condition)
  801. return value <= expected && e == nil, err
  802. case criteriaGe:
  803. value, expected, e = prepareValue(val, criteria.Condition)
  804. return value >= expected && e == nil, err
  805. case criteriaL:
  806. value, expected, e = prepareValue(val, criteria.Condition)
  807. return value < expected && e == nil, err
  808. case criteriaG:
  809. value, expected, e = prepareValue(val, criteria.Condition)
  810. return value > expected && e == nil, err
  811. case criteriaBeg:
  812. return strings.HasPrefix(val, criteria.Condition), err
  813. case criteriaEnd:
  814. return strings.HasSuffix(val, criteria.Condition), err
  815. }
  816. return
  817. }
  818. // Math and Trigonometric functions
  819. // ABS function returns the absolute value of any supplied number. The syntax
  820. // of the function is:
  821. //
  822. // ABS(number)
  823. //
  824. func (fn *formulaFuncs) ABS(argsList *list.List) (result string, err error) {
  825. if argsList.Len() != 1 {
  826. err = errors.New("ABS requires 1 numeric argument")
  827. return
  828. }
  829. var val float64
  830. if val, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).String, 64); err != nil {
  831. err = errors.New(formulaErrorVALUE)
  832. return
  833. }
  834. result = fmt.Sprintf("%g", math.Abs(val))
  835. return
  836. }
  837. // ACOS function calculates the arccosine (i.e. the inverse cosine) of a given
  838. // number, and returns an angle, in radians, between 0 and π. The syntax of
  839. // the function is:
  840. //
  841. // ACOS(number)
  842. //
  843. func (fn *formulaFuncs) ACOS(argsList *list.List) (result string, err error) {
  844. if argsList.Len() != 1 {
  845. err = errors.New("ACOS requires 1 numeric argument")
  846. return
  847. }
  848. var val float64
  849. if val, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).String, 64); err != nil {
  850. err = errors.New(formulaErrorVALUE)
  851. return
  852. }
  853. result = fmt.Sprintf("%g", math.Acos(val))
  854. return
  855. }
  856. // ACOSH function calculates the inverse hyperbolic cosine of a supplied number.
  857. // of the function is:
  858. //
  859. // ACOSH(number)
  860. //
  861. func (fn *formulaFuncs) ACOSH(argsList *list.List) (result string, err error) {
  862. if argsList.Len() != 1 {
  863. err = errors.New("ACOSH requires 1 numeric argument")
  864. return
  865. }
  866. var val float64
  867. if val, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).String, 64); err != nil {
  868. err = errors.New(formulaErrorVALUE)
  869. return
  870. }
  871. result = fmt.Sprintf("%g", math.Acosh(val))
  872. return
  873. }
  874. // ACOT function calculates the arccotangent (i.e. the inverse cotangent) of a
  875. // given number, and returns an angle, in radians, between 0 and π. The syntax
  876. // of the function is:
  877. //
  878. // ACOT(number)
  879. //
  880. func (fn *formulaFuncs) ACOT(argsList *list.List) (result string, err error) {
  881. if argsList.Len() != 1 {
  882. err = errors.New("ACOT requires 1 numeric argument")
  883. return
  884. }
  885. var val float64
  886. if val, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).String, 64); err != nil {
  887. err = errors.New(formulaErrorVALUE)
  888. return
  889. }
  890. result = fmt.Sprintf("%g", math.Pi/2-math.Atan(val))
  891. return
  892. }
  893. // ACOTH function calculates the hyperbolic arccotangent (coth) of a supplied
  894. // value. The syntax of the function is:
  895. //
  896. // ACOTH(number)
  897. //
  898. func (fn *formulaFuncs) ACOTH(argsList *list.List) (result string, err error) {
  899. if argsList.Len() != 1 {
  900. err = errors.New("ACOTH requires 1 numeric argument")
  901. return
  902. }
  903. var val float64
  904. if val, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).String, 64); err != nil {
  905. err = errors.New(formulaErrorVALUE)
  906. return
  907. }
  908. result = fmt.Sprintf("%g", math.Atanh(1/val))
  909. return
  910. }
  911. // ARABIC function converts a Roman numeral into an Arabic numeral. The syntax
  912. // of the function is:
  913. //
  914. // ARABIC(text)
  915. //
  916. func (fn *formulaFuncs) ARABIC(argsList *list.List) (result string, err error) {
  917. if argsList.Len() != 1 {
  918. err = errors.New("ARABIC requires 1 numeric argument")
  919. return
  920. }
  921. charMap := map[rune]float64{'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}
  922. val, last, prefix := 0.0, 0.0, 1.0
  923. for _, char := range argsList.Front().Value.(formulaArg).String {
  924. digit := 0.0
  925. if char == '-' {
  926. prefix = -1
  927. continue
  928. }
  929. digit, _ = charMap[char]
  930. val += digit
  931. switch {
  932. case last == digit && (last == 5 || last == 50 || last == 500):
  933. result = formulaErrorVALUE
  934. return
  935. case 2*last == digit:
  936. result = formulaErrorVALUE
  937. return
  938. }
  939. if last < digit {
  940. val -= 2 * last
  941. }
  942. last = digit
  943. }
  944. result = fmt.Sprintf("%g", prefix*val)
  945. return
  946. }
  947. // ASIN function calculates the arcsine (i.e. the inverse sine) of a given
  948. // number, and returns an angle, in radians, between -π/2 and π/2. The syntax
  949. // of the function is:
  950. //
  951. // ASIN(number)
  952. //
  953. func (fn *formulaFuncs) ASIN(argsList *list.List) (result string, err error) {
  954. if argsList.Len() != 1 {
  955. err = errors.New("ASIN requires 1 numeric argument")
  956. return
  957. }
  958. var val float64
  959. if val, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).String, 64); err != nil {
  960. err = errors.New(formulaErrorVALUE)
  961. return
  962. }
  963. result = fmt.Sprintf("%g", math.Asin(val))
  964. return
  965. }
  966. // ASINH function calculates the inverse hyperbolic sine of a supplied number.
  967. // The syntax of the function is:
  968. //
  969. // ASINH(number)
  970. //
  971. func (fn *formulaFuncs) ASINH(argsList *list.List) (result string, err error) {
  972. if argsList.Len() != 1 {
  973. err = errors.New("ASINH requires 1 numeric argument")
  974. return
  975. }
  976. var val float64
  977. if val, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).String, 64); err != nil {
  978. err = errors.New(formulaErrorVALUE)
  979. return
  980. }
  981. result = fmt.Sprintf("%g", math.Asinh(val))
  982. return
  983. }
  984. // ATAN function calculates the arctangent (i.e. the inverse tangent) of a
  985. // given number, and returns an angle, in radians, between -π/2 and +π/2. The
  986. // syntax of the function is:
  987. //
  988. // ATAN(number)
  989. //
  990. func (fn *formulaFuncs) ATAN(argsList *list.List) (result string, err error) {
  991. if argsList.Len() != 1 {
  992. err = errors.New("ATAN requires 1 numeric argument")
  993. return
  994. }
  995. var val float64
  996. if val, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).String, 64); err != nil {
  997. err = errors.New(formulaErrorVALUE)
  998. return
  999. }
  1000. result = fmt.Sprintf("%g", math.Atan(val))
  1001. return
  1002. }
  1003. // ATANH function calculates the inverse hyperbolic tangent of a supplied
  1004. // number. The syntax of the function is:
  1005. //
  1006. // ATANH(number)
  1007. //
  1008. func (fn *formulaFuncs) ATANH(argsList *list.List) (result string, err error) {
  1009. if argsList.Len() != 1 {
  1010. err = errors.New("ATANH requires 1 numeric argument")
  1011. return
  1012. }
  1013. var val float64
  1014. if val, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).String, 64); err != nil {
  1015. err = errors.New(formulaErrorVALUE)
  1016. return
  1017. }
  1018. result = fmt.Sprintf("%g", math.Atanh(val))
  1019. return
  1020. }
  1021. // ATAN2 function calculates the arctangent (i.e. the inverse tangent) of a
  1022. // given set of x and y coordinates, and returns an angle, in radians, between
  1023. // -π/2 and +π/2. The syntax of the function is:
  1024. //
  1025. // ATAN2(x_num,y_num)
  1026. //
  1027. func (fn *formulaFuncs) ATAN2(argsList *list.List) (result string, err error) {
  1028. if argsList.Len() != 2 {
  1029. err = errors.New("ATAN2 requires 2 numeric arguments")
  1030. return
  1031. }
  1032. var x, y float64
  1033. if x, err = strconv.ParseFloat(argsList.Back().Value.(formulaArg).String, 64); err != nil {
  1034. err = errors.New(formulaErrorVALUE)
  1035. return
  1036. }
  1037. if y, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).String, 64); err != nil {
  1038. err = errors.New(formulaErrorVALUE)
  1039. return
  1040. }
  1041. result = fmt.Sprintf("%g", math.Atan2(x, y))
  1042. return
  1043. }
  1044. // BASE function converts a number into a supplied base (radix), and returns a
  1045. // text representation of the calculated value. The syntax of the function is:
  1046. //
  1047. // BASE(number,radix,[min_length])
  1048. //
  1049. func (fn *formulaFuncs) BASE(argsList *list.List) (result string, err error) {
  1050. if argsList.Len() < 2 {
  1051. err = errors.New("BASE requires at least 2 arguments")
  1052. return
  1053. }
  1054. if argsList.Len() > 3 {
  1055. err = errors.New("BASE allows at most 3 arguments")
  1056. return
  1057. }
  1058. var number float64
  1059. var radix, minLength int
  1060. if number, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).String, 64); err != nil {
  1061. err = errors.New(formulaErrorVALUE)
  1062. return
  1063. }
  1064. if radix, err = strconv.Atoi(argsList.Front().Next().Value.(formulaArg).String); err != nil {
  1065. err = errors.New(formulaErrorVALUE)
  1066. return
  1067. }
  1068. if radix < 2 || radix > 36 {
  1069. err = errors.New("radix must be an integer >= 2 and <= 36")
  1070. return
  1071. }
  1072. if argsList.Len() > 2 {
  1073. if minLength, err = strconv.Atoi(argsList.Back().Value.(formulaArg).String); err != nil {
  1074. err = errors.New(formulaErrorVALUE)
  1075. return
  1076. }
  1077. }
  1078. result = strconv.FormatInt(int64(number), radix)
  1079. if len(result) < minLength {
  1080. result = strings.Repeat("0", minLength-len(result)) + result
  1081. }
  1082. result = strings.ToUpper(result)
  1083. return
  1084. }
  1085. // CEILING function rounds a supplied number away from zero, to the nearest
  1086. // multiple of a given number. The syntax of the function is:
  1087. //
  1088. // CEILING(number,significance)
  1089. //
  1090. func (fn *formulaFuncs) CEILING(argsList *list.List) (result string, err error) {
  1091. if argsList.Len() == 0 {
  1092. err = errors.New("CEILING requires at least 1 argument")
  1093. return
  1094. }
  1095. if argsList.Len() > 2 {
  1096. err = errors.New("CEILING allows at most 2 arguments")
  1097. return
  1098. }
  1099. number, significance, res := 0.0, 1.0, 0.0
  1100. if number, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).String, 64); err != nil {
  1101. err = errors.New(formulaErrorVALUE)
  1102. return
  1103. }
  1104. if number < 0 {
  1105. significance = -1
  1106. }
  1107. if argsList.Len() > 1 {
  1108. if significance, err = strconv.ParseFloat(argsList.Back().Value.(formulaArg).String, 64); err != nil {
  1109. err = errors.New(formulaErrorVALUE)
  1110. return
  1111. }
  1112. }
  1113. if significance < 0 && number > 0 {
  1114. err = errors.New("negative sig to CEILING invalid")
  1115. return
  1116. }
  1117. if argsList.Len() == 1 {
  1118. result = fmt.Sprintf("%g", math.Ceil(number))
  1119. return
  1120. }
  1121. number, res = math.Modf(number / significance)
  1122. if res > 0 {
  1123. number++
  1124. }
  1125. result = fmt.Sprintf("%g", number*significance)
  1126. return
  1127. }
  1128. // CEILINGMATH function rounds a supplied number up to a supplied multiple of
  1129. // significance. The syntax of the function is:
  1130. //
  1131. // CEILING.MATH(number,[significance],[mode])
  1132. //
  1133. func (fn *formulaFuncs) CEILINGMATH(argsList *list.List) (result string, err error) {
  1134. if argsList.Len() == 0 {
  1135. err = errors.New("CEILING.MATH requires at least 1 argument")
  1136. return
  1137. }
  1138. if argsList.Len() > 3 {
  1139. err = errors.New("CEILING.MATH allows at most 3 arguments")
  1140. return
  1141. }
  1142. number, significance, mode := 0.0, 1.0, 1.0
  1143. if number, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).String, 64); err != nil {
  1144. err = errors.New(formulaErrorVALUE)
  1145. return
  1146. }
  1147. if number < 0 {
  1148. significance = -1
  1149. }
  1150. if argsList.Len() > 1 {
  1151. if significance, err = strconv.ParseFloat(argsList.Front().Next().Value.(formulaArg).String, 64); err != nil {
  1152. err = errors.New(formulaErrorVALUE)
  1153. return
  1154. }
  1155. }
  1156. if argsList.Len() == 1 {
  1157. result = fmt.Sprintf("%g", math.Ceil(number))
  1158. return
  1159. }
  1160. if argsList.Len() > 2 {
  1161. if mode, err = strconv.ParseFloat(argsList.Back().Value.(formulaArg).String, 64); err != nil {
  1162. err = errors.New(formulaErrorVALUE)
  1163. return
  1164. }
  1165. }
  1166. val, res := math.Modf(number / significance)
  1167. if res != 0 {
  1168. if number > 0 {
  1169. val++
  1170. } else if mode < 0 {
  1171. val--
  1172. }
  1173. }
  1174. result = fmt.Sprintf("%g", val*significance)
  1175. return
  1176. }
  1177. // CEILINGPRECISE function rounds a supplied number up (regardless of the
  1178. // number's sign), to the nearest multiple of a given number. The syntax of
  1179. // the function is:
  1180. //
  1181. // CEILING.PRECISE(number,[significance])
  1182. //
  1183. func (fn *formulaFuncs) CEILINGPRECISE(argsList *list.List) (result string, err error) {
  1184. if argsList.Len() == 0 {
  1185. err = errors.New("CEILING.PRECISE requires at least 1 argument")
  1186. return
  1187. }
  1188. if argsList.Len() > 2 {
  1189. err = errors.New("CEILING.PRECISE allows at most 2 arguments")
  1190. return
  1191. }
  1192. number, significance := 0.0, 1.0
  1193. if number, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).String, 64); err != nil {
  1194. err = errors.New(formulaErrorVALUE)
  1195. return
  1196. }
  1197. if number < 0 {
  1198. significance = -1
  1199. }
  1200. if argsList.Len() == 1 {
  1201. result = fmt.Sprintf("%g", math.Ceil(number))
  1202. return
  1203. }
  1204. if argsList.Len() > 1 {
  1205. if significance, err = strconv.ParseFloat(argsList.Back().Value.(formulaArg).String, 64); err != nil {
  1206. err = errors.New(formulaErrorVALUE)
  1207. return
  1208. }
  1209. significance = math.Abs(significance)
  1210. if significance == 0 {
  1211. result = "0"
  1212. return
  1213. }
  1214. }
  1215. val, res := math.Modf(number / significance)
  1216. if res != 0 {
  1217. if number > 0 {
  1218. val++
  1219. }
  1220. }
  1221. result = fmt.Sprintf("%g", val*significance)
  1222. return
  1223. }
  1224. // COMBIN function calculates the number of combinations (in any order) of a
  1225. // given number objects from a set. The syntax of the function is:
  1226. //
  1227. // COMBIN(number,number_chosen)
  1228. //
  1229. func (fn *formulaFuncs) COMBIN(argsList *list.List) (result string, err error) {
  1230. if argsList.Len() != 2 {
  1231. err = errors.New("COMBIN requires 2 argument")
  1232. return
  1233. }
  1234. number, chosen, val := 0.0, 0.0, 1.0
  1235. if number, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).String, 64); err != nil {
  1236. err = errors.New(formulaErrorVALUE)
  1237. return
  1238. }
  1239. if chosen, err = strconv.ParseFloat(argsList.Back().Value.(formulaArg).String, 64); err != nil {
  1240. err = errors.New(formulaErrorVALUE)
  1241. return
  1242. }
  1243. number, chosen = math.Trunc(number), math.Trunc(chosen)
  1244. if chosen > number {
  1245. err = errors.New("COMBIN requires number >= number_chosen")
  1246. return
  1247. }
  1248. if chosen == number || chosen == 0 {
  1249. result = "1"
  1250. return
  1251. }
  1252. for c := float64(1); c <= chosen; c++ {
  1253. val *= (number + 1 - c) / c
  1254. }
  1255. result = fmt.Sprintf("%g", math.Ceil(val))
  1256. return
  1257. }
  1258. // COMBINA function calculates the number of combinations, with repetitions,
  1259. // of a given number objects from a set. The syntax of the function is:
  1260. //
  1261. // COMBINA(number,number_chosen)
  1262. //
  1263. func (fn *formulaFuncs) COMBINA(argsList *list.List) (result string, err error) {
  1264. if argsList.Len() != 2 {
  1265. err = errors.New("COMBINA requires 2 argument")
  1266. return
  1267. }
  1268. var number, chosen float64
  1269. if number, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).String, 64); err != nil {
  1270. err = errors.New(formulaErrorVALUE)
  1271. return
  1272. }
  1273. if chosen, err = strconv.ParseFloat(argsList.Back().Value.(formulaArg).String, 64); err != nil {
  1274. err = errors.New(formulaErrorVALUE)
  1275. return
  1276. }
  1277. number, chosen = math.Trunc(number), math.Trunc(chosen)
  1278. if number < chosen {
  1279. err = errors.New("COMBINA requires number > number_chosen")
  1280. return
  1281. }
  1282. if number == 0 {
  1283. result = "0"
  1284. return
  1285. }
  1286. args := list.New()
  1287. args.PushBack(formulaArg{
  1288. String: fmt.Sprintf("%g", number+chosen-1),
  1289. Type: ArgString,
  1290. })
  1291. args.PushBack(formulaArg{
  1292. String: fmt.Sprintf("%g", number-1),
  1293. Type: ArgString,
  1294. })
  1295. return fn.COMBIN(args)
  1296. }
  1297. // COS function calculates the cosine of a given angle. The syntax of the
  1298. // function is:
  1299. //
  1300. // COS(number)
  1301. //
  1302. func (fn *formulaFuncs) COS(argsList *list.List) (result string, err error) {
  1303. if argsList.Len() != 1 {
  1304. err = errors.New("COS requires 1 numeric argument")
  1305. return
  1306. }
  1307. var val float64
  1308. if val, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).String, 64); err != nil {
  1309. err = errors.New(formulaErrorVALUE)
  1310. return
  1311. }
  1312. result = fmt.Sprintf("%g", math.Cos(val))
  1313. return
  1314. }
  1315. // COSH function calculates the hyperbolic cosine (cosh) of a supplied number.
  1316. // The syntax of the function is:
  1317. //
  1318. // COSH(number)
  1319. //
  1320. func (fn *formulaFuncs) COSH(argsList *list.List) (result string, err error) {
  1321. if argsList.Len() != 1 {
  1322. err = errors.New("COSH requires 1 numeric argument")
  1323. return
  1324. }
  1325. var val float64
  1326. if val, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).String, 64); err != nil {
  1327. err = errors.New(formulaErrorVALUE)
  1328. return
  1329. }
  1330. result = fmt.Sprintf("%g", math.Cosh(val))
  1331. return
  1332. }
  1333. // COT function calculates the cotangent of a given angle. The syntax of the
  1334. // function is:
  1335. //
  1336. // COT(number)
  1337. //
  1338. func (fn *formulaFuncs) COT(argsList *list.List) (result string, err error) {
  1339. if argsList.Len() != 1 {
  1340. err = errors.New("COT requires 1 numeric argument")
  1341. return
  1342. }
  1343. var val float64
  1344. if val, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).String, 64); err != nil {
  1345. err = errors.New(formulaErrorVALUE)
  1346. return
  1347. }
  1348. if val == 0 {
  1349. err = errors.New(formulaErrorDIV)
  1350. return
  1351. }
  1352. result = fmt.Sprintf("%g", math.Tan(val))
  1353. return
  1354. }
  1355. // COTH function calculates the hyperbolic cotangent (coth) of a supplied
  1356. // angle. The syntax of the function is:
  1357. //
  1358. // COTH(number)
  1359. //
  1360. func (fn *formulaFuncs) COTH(argsList *list.List) (result string, err error) {
  1361. if argsList.Len() != 1 {
  1362. err = errors.New("COTH requires 1 numeric argument")
  1363. return
  1364. }
  1365. var val float64
  1366. if val, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).String, 64); err != nil {
  1367. err = errors.New(formulaErrorVALUE)
  1368. return
  1369. }
  1370. if val == 0 {
  1371. err = errors.New(formulaErrorDIV)
  1372. return
  1373. }
  1374. result = fmt.Sprintf("%g", math.Tanh(val))
  1375. return
  1376. }
  1377. // CSC function calculates the cosecant of a given angle. The syntax of the
  1378. // function is:
  1379. //
  1380. // CSC(number)
  1381. //
  1382. func (fn *formulaFuncs) CSC(argsList *list.List) (result string, err error) {
  1383. if argsList.Len() != 1 {
  1384. err = errors.New("CSC requires 1 numeric argument")
  1385. return
  1386. }
  1387. var val float64
  1388. if val, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).String, 64); err != nil {
  1389. err = errors.New(formulaErrorVALUE)
  1390. return
  1391. }
  1392. if val == 0 {
  1393. err = errors.New(formulaErrorDIV)
  1394. return
  1395. }
  1396. result = fmt.Sprintf("%g", 1/math.Sin(val))
  1397. return
  1398. }
  1399. // CSCH function calculates the hyperbolic cosecant (csch) of a supplied
  1400. // angle. The syntax of the function is:
  1401. //
  1402. // CSCH(number)
  1403. //
  1404. func (fn *formulaFuncs) CSCH(argsList *list.List) (result string, err error) {
  1405. if argsList.Len() != 1 {
  1406. err = errors.New("CSCH requires 1 numeric argument")
  1407. return
  1408. }
  1409. var val float64
  1410. if val, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).String, 64); err != nil {
  1411. err = errors.New(formulaErrorVALUE)
  1412. return
  1413. }
  1414. if val == 0 {
  1415. err = errors.New(formulaErrorDIV)
  1416. return
  1417. }
  1418. result = fmt.Sprintf("%g", 1/math.Sinh(val))
  1419. return
  1420. }
  1421. // DECIMAL function converts a text representation of a number in a specified
  1422. // base, into a decimal value. The syntax of the function is:
  1423. //
  1424. // DECIMAL(text,radix)
  1425. //
  1426. func (fn *formulaFuncs) DECIMAL(argsList *list.List) (result string, err error) {
  1427. if argsList.Len() != 2 {
  1428. err = errors.New("DECIMAL requires 2 numeric arguments")
  1429. return
  1430. }
  1431. var text = argsList.Front().Value.(formulaArg).String
  1432. var radix int
  1433. if radix, err = strconv.Atoi(argsList.Back().Value.(formulaArg).String); err != nil {
  1434. err = errors.New(formulaErrorVALUE)
  1435. return
  1436. }
  1437. if len(text) > 2 && (strings.HasPrefix(text, "0x") || strings.HasPrefix(text, "0X")) {
  1438. text = text[2:]
  1439. }
  1440. val, err := strconv.ParseInt(text, radix, 64)
  1441. if err != nil {
  1442. err = errors.New(formulaErrorVALUE)
  1443. return
  1444. }
  1445. result = fmt.Sprintf("%g", float64(val))
  1446. return
  1447. }
  1448. // DEGREES function converts radians into degrees. The syntax of the function
  1449. // is:
  1450. //
  1451. // DEGREES(angle)
  1452. //
  1453. func (fn *formulaFuncs) DEGREES(argsList *list.List) (result string, err error) {
  1454. if argsList.Len() != 1 {
  1455. err = errors.New("DEGREES requires 1 numeric argument")
  1456. return
  1457. }
  1458. var val float64
  1459. if val, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).String, 64); err != nil {
  1460. err = errors.New(formulaErrorVALUE)
  1461. return
  1462. }
  1463. if val == 0 {
  1464. err = errors.New(formulaErrorDIV)
  1465. return
  1466. }
  1467. result = fmt.Sprintf("%g", 180.0/math.Pi*val)
  1468. return
  1469. }
  1470. // EVEN function rounds a supplied number away from zero (i.e. rounds a
  1471. // positive number up and a negative number down), to the next even number.
  1472. // The syntax of the function is:
  1473. //
  1474. // EVEN(number)
  1475. //
  1476. func (fn *formulaFuncs) EVEN(argsList *list.List) (result string, err error) {
  1477. if argsList.Len() != 1 {
  1478. err = errors.New("EVEN requires 1 numeric argument")
  1479. return
  1480. }
  1481. var number float64
  1482. if number, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).String, 64); err != nil {
  1483. err = errors.New(formulaErrorVALUE)
  1484. return
  1485. }
  1486. sign := math.Signbit(number)
  1487. m, frac := math.Modf(number / 2)
  1488. val := m * 2
  1489. if frac != 0 {
  1490. if !sign {
  1491. val += 2
  1492. } else {
  1493. val -= 2
  1494. }
  1495. }
  1496. result = fmt.Sprintf("%g", val)
  1497. return
  1498. }
  1499. // EXP function calculates the value of the mathematical constant e, raised to
  1500. // the power of a given number. The syntax of the function is:
  1501. //
  1502. // EXP(number)
  1503. //
  1504. func (fn *formulaFuncs) EXP(argsList *list.List) (result string, err error) {
  1505. if argsList.Len() != 1 {
  1506. err = errors.New("EXP requires 1 numeric argument")
  1507. return
  1508. }
  1509. var number float64
  1510. if number, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).String, 64); err != nil {
  1511. err = errors.New(formulaErrorVALUE)
  1512. return
  1513. }
  1514. result = strings.ToUpper(fmt.Sprintf("%g", math.Exp(number)))
  1515. return
  1516. }
  1517. // fact returns the factorial of a supplied number.
  1518. func fact(number float64) float64 {
  1519. val := float64(1)
  1520. for i := float64(2); i <= number; i++ {
  1521. val *= i
  1522. }
  1523. return val
  1524. }
  1525. // FACT function returns the factorial of a supplied number. The syntax of the
  1526. // function is:
  1527. //
  1528. // FACT(number)
  1529. //
  1530. func (fn *formulaFuncs) FACT(argsList *list.List) (result string, err error) {
  1531. if argsList.Len() != 1 {
  1532. err = errors.New("FACT requires 1 numeric argument")
  1533. return
  1534. }
  1535. var number float64
  1536. if number, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).String, 64); err != nil {
  1537. err = errors.New(formulaErrorVALUE)
  1538. return
  1539. }
  1540. if number < 0 {
  1541. err = errors.New(formulaErrorNUM)
  1542. }
  1543. result = strings.ToUpper(fmt.Sprintf("%g", fact(number)))
  1544. return
  1545. }
  1546. // FACTDOUBLE function returns the double factorial of a supplied number. The
  1547. // syntax of the function is:
  1548. //
  1549. // FACTDOUBLE(number)
  1550. //
  1551. func (fn *formulaFuncs) FACTDOUBLE(argsList *list.List) (result string, err error) {
  1552. if argsList.Len() != 1 {
  1553. err = errors.New("FACTDOUBLE requires 1 numeric argument")
  1554. return
  1555. }
  1556. number, val := 0.0, 1.0
  1557. if number, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).String, 64); err != nil {
  1558. err = errors.New(formulaErrorVALUE)
  1559. return
  1560. }
  1561. if number < 0 {
  1562. err = errors.New(formulaErrorNUM)
  1563. return
  1564. }
  1565. for i := math.Trunc(number); i > 1; i -= 2 {
  1566. val *= i
  1567. }
  1568. result = strings.ToUpper(fmt.Sprintf("%g", val))
  1569. return
  1570. }
  1571. // FLOOR function rounds a supplied number towards zero to the nearest
  1572. // multiple of a specified significance. The syntax of the function is:
  1573. //
  1574. // FLOOR(number,significance)
  1575. //
  1576. func (fn *formulaFuncs) FLOOR(argsList *list.List) (result string, err error) {
  1577. if argsList.Len() != 2 {
  1578. err = errors.New("FLOOR requires 2 numeric arguments")
  1579. return
  1580. }
  1581. var number, significance float64
  1582. if number, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).String, 64); err != nil {
  1583. err = errors.New(formulaErrorVALUE)
  1584. return
  1585. }
  1586. if significance, err = strconv.ParseFloat(argsList.Back().Value.(formulaArg).String, 64); err != nil {
  1587. err = errors.New(formulaErrorVALUE)
  1588. return
  1589. }
  1590. if significance < 0 && number >= 0 {
  1591. err = errors.New(formulaErrorNUM)
  1592. return
  1593. }
  1594. val := number
  1595. val, res := math.Modf(val / significance)
  1596. if res != 0 {
  1597. if number < 0 && res < 0 {
  1598. val--
  1599. }
  1600. }
  1601. result = strings.ToUpper(fmt.Sprintf("%g", val*significance))
  1602. return
  1603. }
  1604. // FLOORMATH function rounds a supplied number down to a supplied multiple of
  1605. // significance. The syntax of the function is:
  1606. //
  1607. // FLOOR.MATH(number,[significance],[mode])
  1608. //
  1609. func (fn *formulaFuncs) FLOORMATH(argsList *list.List) (result string, err error) {
  1610. if argsList.Len() == 0 {
  1611. err = errors.New("FLOOR.MATH requires at least 1 argument")
  1612. return
  1613. }
  1614. if argsList.Len() > 3 {
  1615. err = errors.New("FLOOR.MATH allows at most 3 arguments")
  1616. return
  1617. }
  1618. number, significance, mode := 0.0, 1.0, 1.0
  1619. if number, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).String, 64); err != nil {
  1620. err = errors.New(formulaErrorVALUE)
  1621. return
  1622. }
  1623. if number < 0 {
  1624. significance = -1
  1625. }
  1626. if argsList.Len() > 1 {
  1627. if significance, err = strconv.ParseFloat(argsList.Front().Next().Value.(formulaArg).String, 64); err != nil {
  1628. err = errors.New(formulaErrorVALUE)
  1629. return
  1630. }
  1631. }
  1632. if argsList.Len() == 1 {
  1633. result = fmt.Sprintf("%g", math.Floor(number))
  1634. return
  1635. }
  1636. if argsList.Len() > 2 {
  1637. if mode, err = strconv.ParseFloat(argsList.Back().Value.(formulaArg).String, 64); err != nil {
  1638. err = errors.New(formulaErrorVALUE)
  1639. return
  1640. }
  1641. }
  1642. val, res := math.Modf(number / significance)
  1643. if res != 0 && number < 0 && mode > 0 {
  1644. val--
  1645. }
  1646. result = fmt.Sprintf("%g", val*significance)
  1647. return
  1648. }
  1649. // FLOORPRECISE function rounds a supplied number down to a supplied multiple
  1650. // of significance. The syntax of the function is:
  1651. //
  1652. // FLOOR.PRECISE(number,[significance])
  1653. //
  1654. func (fn *formulaFuncs) FLOORPRECISE(argsList *list.List) (result string, err error) {
  1655. if argsList.Len() == 0 {
  1656. err = errors.New("FLOOR.PRECISE requires at least 1 argument")
  1657. return
  1658. }
  1659. if argsList.Len() > 2 {
  1660. err = errors.New("FLOOR.PRECISE allows at most 2 arguments")
  1661. return
  1662. }
  1663. var number, significance float64
  1664. if number, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).String, 64); err != nil {
  1665. err = errors.New(formulaErrorVALUE)
  1666. return
  1667. }
  1668. if number < 0 {
  1669. significance = -1
  1670. }
  1671. if argsList.Len() == 1 {
  1672. result = fmt.Sprintf("%g", math.Floor(number))
  1673. return
  1674. }
  1675. if argsList.Len() > 1 {
  1676. if significance, err = strconv.ParseFloat(argsList.Back().Value.(formulaArg).String, 64); err != nil {
  1677. err = errors.New(formulaErrorVALUE)
  1678. return
  1679. }
  1680. significance = math.Abs(significance)
  1681. if significance == 0 {
  1682. result = "0"
  1683. return
  1684. }
  1685. }
  1686. val, res := math.Modf(number / significance)
  1687. if res != 0 {
  1688. if number < 0 {
  1689. val--
  1690. }
  1691. }
  1692. result = fmt.Sprintf("%g", val*significance)
  1693. return
  1694. }
  1695. // gcd returns the greatest common divisor of two supplied integers.
  1696. func gcd(x, y float64) float64 {
  1697. x, y = math.Trunc(x), math.Trunc(y)
  1698. if x == 0 {
  1699. return y
  1700. }
  1701. if y == 0 {
  1702. return x
  1703. }
  1704. for x != y {
  1705. if x > y {
  1706. x = x - y
  1707. } else {
  1708. y = y - x
  1709. }
  1710. }
  1711. return x
  1712. }
  1713. // GCD function returns the greatest common divisor of two or more supplied
  1714. // integers. The syntax of the function is:
  1715. //
  1716. // GCD(number1,[number2],...)
  1717. //
  1718. func (fn *formulaFuncs) GCD(argsList *list.List) (result string, err error) {
  1719. if argsList.Len() == 0 {
  1720. err = errors.New("GCD requires at least 1 argument")
  1721. return
  1722. }
  1723. var (
  1724. val float64
  1725. nums = []float64{}
  1726. )
  1727. for arg := argsList.Front(); arg != nil; arg = arg.Next() {
  1728. token := arg.Value.(formulaArg).String
  1729. if token == "" {
  1730. continue
  1731. }
  1732. if val, err = strconv.ParseFloat(token, 64); err != nil {
  1733. err = errors.New(formulaErrorVALUE)
  1734. return
  1735. }
  1736. nums = append(nums, val)
  1737. }
  1738. if nums[0] < 0 {
  1739. err = errors.New("GCD only accepts positive arguments")
  1740. return
  1741. }
  1742. if len(nums) == 1 {
  1743. result = fmt.Sprintf("%g", nums[0])
  1744. return
  1745. }
  1746. cd := nums[0]
  1747. for i := 1; i < len(nums); i++ {
  1748. if nums[i] < 0 {
  1749. err = errors.New("GCD only accepts positive arguments")
  1750. return
  1751. }
  1752. cd = gcd(cd, nums[i])
  1753. }
  1754. result = fmt.Sprintf("%g", cd)
  1755. return
  1756. }
  1757. // INT function truncates a supplied number down to the closest integer. The
  1758. // syntax of the function is:
  1759. //
  1760. // INT(number)
  1761. //
  1762. func (fn *formulaFuncs) INT(argsList *list.List) (result string, err error) {
  1763. if argsList.Len() != 1 {
  1764. err = errors.New("INT requires 1 numeric argument")
  1765. return
  1766. }
  1767. var number float64
  1768. if number, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).String, 64); err != nil {
  1769. err = errors.New(formulaErrorVALUE)
  1770. return
  1771. }
  1772. val, frac := math.Modf(number)
  1773. if frac < 0 {
  1774. val--
  1775. }
  1776. result = fmt.Sprintf("%g", val)
  1777. return
  1778. }
  1779. // ISOCEILING function rounds a supplied number up (regardless of the number's
  1780. // sign), to the nearest multiple of a supplied significance. The syntax of
  1781. // the function is:
  1782. //
  1783. // ISO.CEILING(number,[significance])
  1784. //
  1785. func (fn *formulaFuncs) ISOCEILING(argsList *list.List) (result string, err error) {
  1786. if argsList.Len() == 0 {
  1787. err = errors.New("ISO.CEILING requires at least 1 argument")
  1788. return
  1789. }
  1790. if argsList.Len() > 2 {
  1791. err = errors.New("ISO.CEILING allows at most 2 arguments")
  1792. return
  1793. }
  1794. var number, significance float64
  1795. if number, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).String, 64); err != nil {
  1796. err = errors.New(formulaErrorVALUE)
  1797. return
  1798. }
  1799. if number < 0 {
  1800. significance = -1
  1801. }
  1802. if argsList.Len() == 1 {
  1803. result = fmt.Sprintf("%g", math.Ceil(number))
  1804. return
  1805. }
  1806. if argsList.Len() > 1 {
  1807. if significance, err = strconv.ParseFloat(argsList.Back().Value.(formulaArg).String, 64); err != nil {
  1808. err = errors.New(formulaErrorVALUE)
  1809. return
  1810. }
  1811. significance = math.Abs(significance)
  1812. if significance == 0 {
  1813. result = "0"
  1814. return
  1815. }
  1816. }
  1817. val, res := math.Modf(number / significance)
  1818. if res != 0 {
  1819. if number > 0 {
  1820. val++
  1821. }
  1822. }
  1823. result = fmt.Sprintf("%g", val*significance)
  1824. return
  1825. }
  1826. // lcm returns the least common multiple of two supplied integers.
  1827. func lcm(a, b float64) float64 {
  1828. a = math.Trunc(a)
  1829. b = math.Trunc(b)
  1830. if a == 0 && b == 0 {
  1831. return 0
  1832. }
  1833. return a * b / gcd(a, b)
  1834. }
  1835. // LCM function returns the least common multiple of two or more supplied
  1836. // integers. The syntax of the function is:
  1837. //
  1838. // LCM(number1,[number2],...)
  1839. //
  1840. func (fn *formulaFuncs) LCM(argsList *list.List) (result string, err error) {
  1841. if argsList.Len() == 0 {
  1842. err = errors.New("LCM requires at least 1 argument")
  1843. return
  1844. }
  1845. var (
  1846. val float64
  1847. nums = []float64{}
  1848. )
  1849. for arg := argsList.Front(); arg != nil; arg = arg.Next() {
  1850. token := arg.Value.(formulaArg).String
  1851. if token == "" {
  1852. continue
  1853. }
  1854. if val, err = strconv.ParseFloat(token, 64); err != nil {
  1855. err = errors.New(formulaErrorVALUE)
  1856. return
  1857. }
  1858. nums = append(nums, val)
  1859. }
  1860. if nums[0] < 0 {
  1861. err = errors.New("LCM only accepts positive arguments")
  1862. return
  1863. }
  1864. if len(nums) == 1 {
  1865. result = fmt.Sprintf("%g", nums[0])
  1866. return
  1867. }
  1868. cm := nums[0]
  1869. for i := 1; i < len(nums); i++ {
  1870. if nums[i] < 0 {
  1871. err = errors.New("LCM only accepts positive arguments")
  1872. return
  1873. }
  1874. cm = lcm(cm, nums[i])
  1875. }
  1876. result = fmt.Sprintf("%g", cm)
  1877. return
  1878. }
  1879. // LN function calculates the natural logarithm of a given number. The syntax
  1880. // of the function is:
  1881. //
  1882. // LN(number)
  1883. //
  1884. func (fn *formulaFuncs) LN(argsList *list.List) (result string, err error) {
  1885. if argsList.Len() != 1 {
  1886. err = errors.New("LN requires 1 numeric argument")
  1887. return
  1888. }
  1889. var number float64
  1890. if number, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).String, 64); err != nil {
  1891. err = errors.New(formulaErrorVALUE)
  1892. return
  1893. }
  1894. result = fmt.Sprintf("%g", math.Log(number))
  1895. return
  1896. }
  1897. // LOG function calculates the logarithm of a given number, to a supplied
  1898. // base. The syntax of the function is:
  1899. //
  1900. // LOG(number,[base])
  1901. //
  1902. func (fn *formulaFuncs) LOG(argsList *list.List) (result string, err error) {
  1903. if argsList.Len() == 0 {
  1904. err = errors.New("LOG requires at least 1 argument")
  1905. return
  1906. }
  1907. if argsList.Len() > 2 {
  1908. err = errors.New("LOG allows at most 2 arguments")
  1909. return
  1910. }
  1911. number, base := 0.0, 10.0
  1912. if number, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).String, 64); err != nil {
  1913. err = errors.New(formulaErrorVALUE)
  1914. return
  1915. }
  1916. if argsList.Len() > 1 {
  1917. if base, err = strconv.ParseFloat(argsList.Back().Value.(formulaArg).String, 64); err != nil {
  1918. err = errors.New(formulaErrorVALUE)
  1919. return
  1920. }
  1921. }
  1922. if number == 0 {
  1923. err = errors.New(formulaErrorNUM)
  1924. return
  1925. }
  1926. if base == 0 {
  1927. err = errors.New(formulaErrorNUM)
  1928. return
  1929. }
  1930. if base == 1 {
  1931. err = errors.New(formulaErrorDIV)
  1932. return
  1933. }
  1934. result = fmt.Sprintf("%g", math.Log(number)/math.Log(base))
  1935. return
  1936. }
  1937. // LOG10 function calculates the base 10 logarithm of a given number. The
  1938. // syntax of the function is:
  1939. //
  1940. // LOG10(number)
  1941. //
  1942. func (fn *formulaFuncs) LOG10(argsList *list.List) (result string, err error) {
  1943. if argsList.Len() != 1 {
  1944. err = errors.New("LOG10 requires 1 numeric argument")
  1945. return
  1946. }
  1947. var number float64
  1948. if number, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).String, 64); err != nil {
  1949. err = errors.New(formulaErrorVALUE)
  1950. return
  1951. }
  1952. result = fmt.Sprintf("%g", math.Log10(number))
  1953. return
  1954. }
  1955. func minor(sqMtx [][]float64, idx int) [][]float64 {
  1956. ret := [][]float64{}
  1957. for i := range sqMtx {
  1958. if i == 0 {
  1959. continue
  1960. }
  1961. row := []float64{}
  1962. for j := range sqMtx {
  1963. if j == idx {
  1964. continue
  1965. }
  1966. row = append(row, sqMtx[i][j])
  1967. }
  1968. ret = append(ret, row)
  1969. }
  1970. return ret
  1971. }
  1972. // det determinant of the 2x2 matrix.
  1973. func det(sqMtx [][]float64) float64 {
  1974. if len(sqMtx) == 2 {
  1975. m00 := sqMtx[0][0]
  1976. m01 := sqMtx[0][1]
  1977. m10 := sqMtx[1][0]
  1978. m11 := sqMtx[1][1]
  1979. return m00*m11 - m10*m01
  1980. }
  1981. var res, sgn float64 = 0, 1
  1982. for j := range sqMtx {
  1983. res += sgn * sqMtx[0][j] * det(minor(sqMtx, j))
  1984. sgn *= -1
  1985. }
  1986. return res
  1987. }
  1988. // MDETERM calculates the determinant of a square matrix. The
  1989. // syntax of the function is:
  1990. //
  1991. // MDETERM(array)
  1992. //
  1993. func (fn *formulaFuncs) MDETERM(argsList *list.List) (result string, err error) {
  1994. var num float64
  1995. var numMtx = [][]float64{}
  1996. var strMtx = argsList.Front().Value.(formulaArg).Matrix
  1997. if argsList.Len() < 1 {
  1998. return
  1999. }
  2000. var rows = len(strMtx)
  2001. for _, row := range argsList.Front().Value.(formulaArg).Matrix {
  2002. if len(row) != rows {
  2003. err = errors.New(formulaErrorVALUE)
  2004. return
  2005. }
  2006. numRow := []float64{}
  2007. for _, ele := range row {
  2008. if num, err = strconv.ParseFloat(ele.String, 64); err != nil {
  2009. return
  2010. }
  2011. numRow = append(numRow, num)
  2012. }
  2013. numMtx = append(numMtx, numRow)
  2014. }
  2015. result = fmt.Sprintf("%g", det(numMtx))
  2016. return
  2017. }
  2018. // MOD function returns the remainder of a division between two supplied
  2019. // numbers. The syntax of the function is:
  2020. //
  2021. // MOD(number,divisor)
  2022. //
  2023. func (fn *formulaFuncs) MOD(argsList *list.List) (result string, err error) {
  2024. if argsList.Len() != 2 {
  2025. err = errors.New("MOD requires 2 numeric arguments")
  2026. return
  2027. }
  2028. var number, divisor float64
  2029. if number, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).String, 64); err != nil {
  2030. err = errors.New(formulaErrorVALUE)
  2031. return
  2032. }
  2033. if divisor, err = strconv.ParseFloat(argsList.Back().Value.(formulaArg).String, 64); err != nil {
  2034. err = errors.New(formulaErrorVALUE)
  2035. return
  2036. }
  2037. if divisor == 0 {
  2038. err = errors.New(formulaErrorDIV)
  2039. return
  2040. }
  2041. trunc, rem := math.Modf(number / divisor)
  2042. if rem < 0 {
  2043. trunc--
  2044. }
  2045. result = fmt.Sprintf("%g", number-divisor*trunc)
  2046. return
  2047. }
  2048. // MROUND function rounds a supplied number up or down to the nearest multiple
  2049. // of a given number. The syntax of the function is:
  2050. //
  2051. // MROUND(number,multiple)
  2052. //
  2053. func (fn *formulaFuncs) MROUND(argsList *list.List) (result string, err error) {
  2054. if argsList.Len() != 2 {
  2055. err = errors.New("MROUND requires 2 numeric arguments")
  2056. return
  2057. }
  2058. var number, multiple float64
  2059. if number, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).String, 64); err != nil {
  2060. err = errors.New(formulaErrorVALUE)
  2061. return
  2062. }
  2063. if multiple, err = strconv.ParseFloat(argsList.Back().Value.(formulaArg).String, 64); err != nil {
  2064. err = errors.New(formulaErrorVALUE)
  2065. return
  2066. }
  2067. if multiple == 0 {
  2068. err = errors.New(formulaErrorNUM)
  2069. return
  2070. }
  2071. if multiple < 0 && number > 0 ||
  2072. multiple > 0 && number < 0 {
  2073. err = errors.New(formulaErrorNUM)
  2074. return
  2075. }
  2076. number, res := math.Modf(number / multiple)
  2077. if math.Trunc(res+0.5) > 0 {
  2078. number++
  2079. }
  2080. result = fmt.Sprintf("%g", number*multiple)
  2081. return
  2082. }
  2083. // MULTINOMIAL function calculates the ratio of the factorial of a sum of
  2084. // supplied values to the product of factorials of those values. The syntax of
  2085. // the function is:
  2086. //
  2087. // MULTINOMIAL(number1,[number2],...)
  2088. //
  2089. func (fn *formulaFuncs) MULTINOMIAL(argsList *list.List) (result string, err error) {
  2090. val, num, denom := 0.0, 0.0, 1.0
  2091. for arg := argsList.Front(); arg != nil; arg = arg.Next() {
  2092. token := arg.Value.(formulaArg)
  2093. if token.String == "" {
  2094. continue
  2095. }
  2096. if val, err = strconv.ParseFloat(token.String, 64); err != nil {
  2097. err = errors.New(formulaErrorVALUE)
  2098. return
  2099. }
  2100. num += val
  2101. denom *= fact(val)
  2102. }
  2103. result = fmt.Sprintf("%g", fact(num)/denom)
  2104. return
  2105. }
  2106. // MUNIT function returns the unit matrix for a specified dimension. The
  2107. // syntax of the function is:
  2108. //
  2109. // MUNIT(dimension)
  2110. //
  2111. func (fn *formulaFuncs) MUNIT(argsList *list.List) (result string, err error) {
  2112. if argsList.Len() != 1 {
  2113. err = errors.New("MUNIT requires 1 numeric argument")
  2114. return
  2115. }
  2116. var dimension int
  2117. if dimension, err = strconv.Atoi(argsList.Front().Value.(formulaArg).String); err != nil {
  2118. err = errors.New(formulaErrorVALUE)
  2119. return
  2120. }
  2121. matrix := make([][]float64, 0, dimension)
  2122. for i := 0; i < dimension; i++ {
  2123. row := make([]float64, dimension)
  2124. for j := 0; j < dimension; j++ {
  2125. if i == j {
  2126. row[j] = float64(1.0)
  2127. } else {
  2128. row[j] = float64(0.0)
  2129. }
  2130. }
  2131. matrix = append(matrix, row)
  2132. }
  2133. return
  2134. }
  2135. // ODD function ounds a supplied number away from zero (i.e. rounds a positive
  2136. // number up and a negative number down), to the next odd number. The syntax
  2137. // of the function is:
  2138. //
  2139. // ODD(number)
  2140. //
  2141. func (fn *formulaFuncs) ODD(argsList *list.List) (result string, err error) {
  2142. if argsList.Len() != 1 {
  2143. err = errors.New("ODD requires 1 numeric argument")
  2144. return
  2145. }
  2146. var number float64
  2147. if number, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).String, 64); err != nil {
  2148. err = errors.New(formulaErrorVALUE)
  2149. return
  2150. }
  2151. if number == 0 {
  2152. result = "1"
  2153. return
  2154. }
  2155. sign := math.Signbit(number)
  2156. m, frac := math.Modf((number - 1) / 2)
  2157. val := m*2 + 1
  2158. if frac != 0 {
  2159. if !sign {
  2160. val += 2
  2161. } else {
  2162. val -= 2
  2163. }
  2164. }
  2165. result = fmt.Sprintf("%g", val)
  2166. return
  2167. }
  2168. // PI function returns the value of the mathematical constant π (pi), accurate
  2169. // to 15 digits (14 decimal places). The syntax of the function is:
  2170. //
  2171. // PI()
  2172. //
  2173. func (fn *formulaFuncs) PI(argsList *list.List) (result string, err error) {
  2174. if argsList.Len() != 0 {
  2175. err = errors.New("PI accepts no arguments")
  2176. return
  2177. }
  2178. result = fmt.Sprintf("%g", math.Pi)
  2179. return
  2180. }
  2181. // POWER function calculates a given number, raised to a supplied power.
  2182. // The syntax of the function is:
  2183. //
  2184. // POWER(number,power)
  2185. //
  2186. func (fn *formulaFuncs) POWER(argsList *list.List) (result string, err error) {
  2187. if argsList.Len() != 2 {
  2188. err = errors.New("POWER requires 2 numeric arguments")
  2189. return
  2190. }
  2191. var x, y float64
  2192. if x, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).String, 64); err != nil {
  2193. err = errors.New(formulaErrorVALUE)
  2194. return
  2195. }
  2196. if y, err = strconv.ParseFloat(argsList.Back().Value.(formulaArg).String, 64); err != nil {
  2197. err = errors.New(formulaErrorVALUE)
  2198. return
  2199. }
  2200. if x == 0 && y == 0 {
  2201. err = errors.New(formulaErrorNUM)
  2202. return
  2203. }
  2204. if x == 0 && y < 0 {
  2205. err = errors.New(formulaErrorDIV)
  2206. return
  2207. }
  2208. result = fmt.Sprintf("%g", math.Pow(x, y))
  2209. return
  2210. }
  2211. // PRODUCT function returns the product (multiplication) of a supplied set of
  2212. // numerical values. The syntax of the function is:
  2213. //
  2214. // PRODUCT(number1,[number2],...)
  2215. //
  2216. func (fn *formulaFuncs) PRODUCT(argsList *list.List) (result string, err error) {
  2217. val, product := 0.0, 1.0
  2218. for arg := argsList.Front(); arg != nil; arg = arg.Next() {
  2219. token := arg.Value.(formulaArg)
  2220. switch token.Type {
  2221. case ArgUnknown:
  2222. continue
  2223. case ArgString:
  2224. if token.String == "" {
  2225. continue
  2226. }
  2227. if val, err = strconv.ParseFloat(token.String, 64); err != nil {
  2228. err = errors.New(formulaErrorVALUE)
  2229. return
  2230. }
  2231. product = product * val
  2232. case ArgMatrix:
  2233. for _, row := range token.Matrix {
  2234. for _, value := range row {
  2235. if value.String == "" {
  2236. continue
  2237. }
  2238. if val, err = strconv.ParseFloat(value.String, 64); err != nil {
  2239. err = errors.New(formulaErrorVALUE)
  2240. return
  2241. }
  2242. product = product * val
  2243. }
  2244. }
  2245. }
  2246. }
  2247. result = fmt.Sprintf("%g", product)
  2248. return
  2249. }
  2250. // QUOTIENT function returns the integer portion of a division between two
  2251. // supplied numbers. The syntax of the function is:
  2252. //
  2253. // QUOTIENT(numerator,denominator)
  2254. //
  2255. func (fn *formulaFuncs) QUOTIENT(argsList *list.List) (result string, err error) {
  2256. if argsList.Len() != 2 {
  2257. err = errors.New("QUOTIENT requires 2 numeric arguments")
  2258. return
  2259. }
  2260. var x, y float64
  2261. if x, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).String, 64); err != nil {
  2262. err = errors.New(formulaErrorVALUE)
  2263. return
  2264. }
  2265. if y, err = strconv.ParseFloat(argsList.Back().Value.(formulaArg).String, 64); err != nil {
  2266. err = errors.New(formulaErrorVALUE)
  2267. return
  2268. }
  2269. if y == 0 {
  2270. err = errors.New(formulaErrorDIV)
  2271. return
  2272. }
  2273. result = fmt.Sprintf("%g", math.Trunc(x/y))
  2274. return
  2275. }
  2276. // RADIANS function converts radians into degrees. The syntax of the function is:
  2277. //
  2278. // RADIANS(angle)
  2279. //
  2280. func (fn *formulaFuncs) RADIANS(argsList *list.List) (result string, err error) {
  2281. if argsList.Len() != 1 {
  2282. err = errors.New("RADIANS requires 1 numeric argument")
  2283. return
  2284. }
  2285. var angle float64
  2286. if angle, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).String, 64); err != nil {
  2287. err = errors.New(formulaErrorVALUE)
  2288. return
  2289. }
  2290. result = fmt.Sprintf("%g", math.Pi/180.0*angle)
  2291. return
  2292. }
  2293. // RAND function generates a random real number between 0 and 1. The syntax of
  2294. // the function is:
  2295. //
  2296. // RAND()
  2297. //
  2298. func (fn *formulaFuncs) RAND(argsList *list.List) (result string, err error) {
  2299. if argsList.Len() != 0 {
  2300. err = errors.New("RAND accepts no arguments")
  2301. return
  2302. }
  2303. result = fmt.Sprintf("%g", rand.New(rand.NewSource(time.Now().UnixNano())).Float64())
  2304. return
  2305. }
  2306. // RANDBETWEEN function generates a random integer between two supplied
  2307. // integers. The syntax of the function is:
  2308. //
  2309. // RANDBETWEEN(bottom,top)
  2310. //
  2311. func (fn *formulaFuncs) RANDBETWEEN(argsList *list.List) (result string, err error) {
  2312. if argsList.Len() != 2 {
  2313. err = errors.New("RANDBETWEEN requires 2 numeric arguments")
  2314. return
  2315. }
  2316. var bottom, top int64
  2317. if bottom, err = strconv.ParseInt(argsList.Front().Value.(formulaArg).String, 10, 64); err != nil {
  2318. err = errors.New(formulaErrorVALUE)
  2319. return
  2320. }
  2321. if top, err = strconv.ParseInt(argsList.Back().Value.(formulaArg).String, 10, 64); err != nil {
  2322. err = errors.New(formulaErrorVALUE)
  2323. return
  2324. }
  2325. if top < bottom {
  2326. err = errors.New(formulaErrorNUM)
  2327. return
  2328. }
  2329. result = fmt.Sprintf("%g", float64(rand.New(rand.NewSource(time.Now().UnixNano())).Int63n(top-bottom+1)+bottom))
  2330. return
  2331. }
  2332. // romanNumerals defined a numeral system that originated in ancient Rome and
  2333. // remained the usual way of writing numbers throughout Europe well into the
  2334. // Late Middle Ages.
  2335. type romanNumerals struct {
  2336. n float64
  2337. s string
  2338. }
  2339. var romanTable = [][]romanNumerals{{{1000, "M"}, {900, "CM"}, {500, "D"}, {400, "CD"}, {100, "C"}, {90, "XC"}, {50, "L"}, {40, "XL"}, {10, "X"}, {9, "IX"}, {5, "V"}, {4, "IV"}, {1, "I"}},
  2340. {{1000, "M"}, {950, "LM"}, {900, "CM"}, {500, "D"}, {450, "LD"}, {400, "CD"}, {100, "C"}, {95, "VC"}, {90, "XC"}, {50, "L"}, {45, "VL"}, {40, "XL"}, {10, "X"}, {9, "IX"}, {5, "V"}, {4, "IV"}, {1, "I"}},
  2341. {{1000, "M"}, {990, "XM"}, {950, "LM"}, {900, "CM"}, {500, "D"}, {490, "XD"}, {450, "LD"}, {400, "CD"}, {100, "C"}, {99, "IC"}, {90, "XC"}, {50, "L"}, {45, "VL"}, {40, "XL"}, {10, "X"}, {9, "IX"}, {5, "V"}, {4, "IV"}, {1, "I"}},
  2342. {{1000, "M"}, {995, "VM"}, {990, "XM"}, {950, "LM"}, {900, "CM"}, {500, "D"}, {495, "VD"}, {490, "XD"}, {450, "LD"}, {400, "CD"}, {100, "C"}, {99, "IC"}, {90, "XC"}, {50, "L"}, {45, "VL"}, {40, "XL"}, {10, "X"}, {9, "IX"}, {5, "V"}, {4, "IV"}, {1, "I"}},
  2343. {{1000, "M"}, {999, "IM"}, {995, "VM"}, {990, "XM"}, {950, "LM"}, {900, "CM"}, {500, "D"}, {499, "ID"}, {495, "VD"}, {490, "XD"}, {450, "LD"}, {400, "CD"}, {100, "C"}, {99, "IC"}, {90, "XC"}, {50, "L"}, {45, "VL"}, {40, "XL"}, {10, "X"}, {9, "IX"}, {5, "V"}, {4, "IV"}, {1, "I"}}}
  2344. // ROMAN function converts an arabic number to Roman. I.e. for a supplied
  2345. // integer, the function returns a text string depicting the roman numeral
  2346. // form of the number. The syntax of the function is:
  2347. //
  2348. // ROMAN(number,[form])
  2349. //
  2350. func (fn *formulaFuncs) ROMAN(argsList *list.List) (result string, err error) {
  2351. if argsList.Len() == 0 {
  2352. err = errors.New("ROMAN requires at least 1 argument")
  2353. return
  2354. }
  2355. if argsList.Len() > 2 {
  2356. err = errors.New("ROMAN allows at most 2 arguments")
  2357. return
  2358. }
  2359. var number float64
  2360. var form int
  2361. if number, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).String, 64); err != nil {
  2362. err = errors.New(formulaErrorVALUE)
  2363. return
  2364. }
  2365. if argsList.Len() > 1 {
  2366. if form, err = strconv.Atoi(argsList.Back().Value.(formulaArg).String); err != nil {
  2367. err = errors.New(formulaErrorVALUE)
  2368. return
  2369. }
  2370. if form < 0 {
  2371. form = 0
  2372. } else if form > 4 {
  2373. form = 4
  2374. }
  2375. }
  2376. decimalTable := romanTable[0]
  2377. switch form {
  2378. case 1:
  2379. decimalTable = romanTable[1]
  2380. case 2:
  2381. decimalTable = romanTable[2]
  2382. case 3:
  2383. decimalTable = romanTable[3]
  2384. case 4:
  2385. decimalTable = romanTable[4]
  2386. }
  2387. val := math.Trunc(number)
  2388. buf := bytes.Buffer{}
  2389. for _, r := range decimalTable {
  2390. for val >= r.n {
  2391. buf.WriteString(r.s)
  2392. val -= r.n
  2393. }
  2394. }
  2395. result = buf.String()
  2396. return
  2397. }
  2398. type roundMode byte
  2399. const (
  2400. closest roundMode = iota
  2401. down
  2402. up
  2403. )
  2404. // round rounds a supplied number up or down.
  2405. func (fn *formulaFuncs) round(number, digits float64, mode roundMode) float64 {
  2406. var significance float64
  2407. if digits > 0 {
  2408. significance = math.Pow(1/10.0, digits)
  2409. } else {
  2410. significance = math.Pow(10.0, -digits)
  2411. }
  2412. val, res := math.Modf(number / significance)
  2413. switch mode {
  2414. case closest:
  2415. const eps = 0.499999999
  2416. if res >= eps {
  2417. val++
  2418. } else if res <= -eps {
  2419. val--
  2420. }
  2421. case down:
  2422. case up:
  2423. if res > 0 {
  2424. val++
  2425. } else if res < 0 {
  2426. val--
  2427. }
  2428. }
  2429. return val * significance
  2430. }
  2431. // ROUND function rounds a supplied number up or down, to a specified number
  2432. // of decimal places. The syntax of the function is:
  2433. //
  2434. // ROUND(number,num_digits)
  2435. //
  2436. func (fn *formulaFuncs) ROUND(argsList *list.List) (result string, err error) {
  2437. if argsList.Len() != 2 {
  2438. err = errors.New("ROUND requires 2 numeric arguments")
  2439. return
  2440. }
  2441. var number, digits float64
  2442. if number, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).String, 64); err != nil {
  2443. err = errors.New(formulaErrorVALUE)
  2444. return
  2445. }
  2446. if digits, err = strconv.ParseFloat(argsList.Back().Value.(formulaArg).String, 64); err != nil {
  2447. err = errors.New(formulaErrorVALUE)
  2448. return
  2449. }
  2450. result = fmt.Sprintf("%g", fn.round(number, digits, closest))
  2451. return
  2452. }
  2453. // ROUNDDOWN function rounds a supplied number down towards zero, to a
  2454. // specified number of decimal places. The syntax of the function is:
  2455. //
  2456. // ROUNDDOWN(number,num_digits)
  2457. //
  2458. func (fn *formulaFuncs) ROUNDDOWN(argsList *list.List) (result string, err error) {
  2459. if argsList.Len() != 2 {
  2460. err = errors.New("ROUNDDOWN requires 2 numeric arguments")
  2461. return
  2462. }
  2463. var number, digits float64
  2464. if number, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).String, 64); err != nil {
  2465. err = errors.New(formulaErrorVALUE)
  2466. return
  2467. }
  2468. if digits, err = strconv.ParseFloat(argsList.Back().Value.(formulaArg).String, 64); err != nil {
  2469. err = errors.New(formulaErrorVALUE)
  2470. return
  2471. }
  2472. result = fmt.Sprintf("%g", fn.round(number, digits, down))
  2473. return
  2474. }
  2475. // ROUNDUP function rounds a supplied number up, away from zero, to a
  2476. // specified number of decimal places. The syntax of the function is:
  2477. //
  2478. // ROUNDUP(number,num_digits)
  2479. //
  2480. func (fn *formulaFuncs) ROUNDUP(argsList *list.List) (result string, err error) {
  2481. if argsList.Len() != 2 {
  2482. err = errors.New("ROUNDUP requires 2 numeric arguments")
  2483. return
  2484. }
  2485. var number, digits float64
  2486. if number, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).String, 64); err != nil {
  2487. err = errors.New(formulaErrorVALUE)
  2488. return
  2489. }
  2490. if digits, err = strconv.ParseFloat(argsList.Back().Value.(formulaArg).String, 64); err != nil {
  2491. err = errors.New(formulaErrorVALUE)
  2492. return
  2493. }
  2494. result = fmt.Sprintf("%g", fn.round(number, digits, up))
  2495. return
  2496. }
  2497. // SEC function calculates the secant of a given angle. The syntax of the
  2498. // function is:
  2499. //
  2500. // SEC(number)
  2501. //
  2502. func (fn *formulaFuncs) SEC(argsList *list.List) (result string, err error) {
  2503. if argsList.Len() != 1 {
  2504. err = errors.New("SEC requires 1 numeric argument")
  2505. return
  2506. }
  2507. var number float64
  2508. if number, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).String, 64); err != nil {
  2509. err = errors.New(formulaErrorVALUE)
  2510. return
  2511. }
  2512. result = fmt.Sprintf("%g", math.Cos(number))
  2513. return
  2514. }
  2515. // SECH function calculates the hyperbolic secant (sech) of a supplied angle.
  2516. // The syntax of the function is:
  2517. //
  2518. // SECH(number)
  2519. //
  2520. func (fn *formulaFuncs) SECH(argsList *list.List) (result string, err error) {
  2521. if argsList.Len() != 1 {
  2522. err = errors.New("SECH requires 1 numeric argument")
  2523. return
  2524. }
  2525. var number float64
  2526. if number, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).String, 64); err != nil {
  2527. err = errors.New(formulaErrorVALUE)
  2528. return
  2529. }
  2530. result = fmt.Sprintf("%g", 1/math.Cosh(number))
  2531. return
  2532. }
  2533. // SIGN function returns the arithmetic sign (+1, -1 or 0) of a supplied
  2534. // number. I.e. if the number is positive, the Sign function returns +1, if
  2535. // the number is negative, the function returns -1 and if the number is 0
  2536. // (zero), the function returns 0. The syntax of the function is:
  2537. //
  2538. // SIGN(number)
  2539. //
  2540. func (fn *formulaFuncs) SIGN(argsList *list.List) (result string, err error) {
  2541. if argsList.Len() != 1 {
  2542. err = errors.New("SIGN requires 1 numeric argument")
  2543. return
  2544. }
  2545. var val float64
  2546. if val, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).String, 64); err != nil {
  2547. err = errors.New(formulaErrorVALUE)
  2548. return
  2549. }
  2550. if val < 0 {
  2551. result = "-1"
  2552. return
  2553. }
  2554. if val > 0 {
  2555. result = "1"
  2556. return
  2557. }
  2558. result = "0"
  2559. return
  2560. }
  2561. // SIN function calculates the sine of a given angle. The syntax of the
  2562. // function is:
  2563. //
  2564. // SIN(number)
  2565. //
  2566. func (fn *formulaFuncs) SIN(argsList *list.List) (result string, err error) {
  2567. if argsList.Len() != 1 {
  2568. err = errors.New("SIN requires 1 numeric argument")
  2569. return
  2570. }
  2571. var number float64
  2572. if number, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).String, 64); err != nil {
  2573. err = errors.New(formulaErrorVALUE)
  2574. return
  2575. }
  2576. result = fmt.Sprintf("%g", math.Sin(number))
  2577. return
  2578. }
  2579. // SINH function calculates the hyperbolic sine (sinh) of a supplied number.
  2580. // The syntax of the function is:
  2581. //
  2582. // SINH(number)
  2583. //
  2584. func (fn *formulaFuncs) SINH(argsList *list.List) (result string, err error) {
  2585. if argsList.Len() != 1 {
  2586. err = errors.New("SINH requires 1 numeric argument")
  2587. return
  2588. }
  2589. var number float64
  2590. if number, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).String, 64); err != nil {
  2591. err = errors.New(formulaErrorVALUE)
  2592. return
  2593. }
  2594. result = fmt.Sprintf("%g", math.Sinh(number))
  2595. return
  2596. }
  2597. // SQRT function calculates the positive square root of a supplied number. The
  2598. // syntax of the function is:
  2599. //
  2600. // SQRT(number)
  2601. //
  2602. func (fn *formulaFuncs) SQRT(argsList *list.List) (result string, err error) {
  2603. if argsList.Len() != 1 {
  2604. err = errors.New("SQRT requires 1 numeric argument")
  2605. return
  2606. }
  2607. var res float64
  2608. var value = argsList.Front().Value.(formulaArg).String
  2609. if value == "" {
  2610. result = "0"
  2611. return
  2612. }
  2613. if res, err = strconv.ParseFloat(value, 64); err != nil {
  2614. err = errors.New(formulaErrorVALUE)
  2615. return
  2616. }
  2617. if res < 0 {
  2618. err = errors.New(formulaErrorNUM)
  2619. return
  2620. }
  2621. result = fmt.Sprintf("%g", math.Sqrt(res))
  2622. return
  2623. }
  2624. // SQRTPI function returns the square root of a supplied number multiplied by
  2625. // the mathematical constant, π. The syntax of the function is:
  2626. //
  2627. // SQRTPI(number)
  2628. //
  2629. func (fn *formulaFuncs) SQRTPI(argsList *list.List) (result string, err error) {
  2630. if argsList.Len() != 1 {
  2631. err = errors.New("SQRTPI requires 1 numeric argument")
  2632. return
  2633. }
  2634. var number float64
  2635. if number, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).String, 64); err != nil {
  2636. err = errors.New(formulaErrorVALUE)
  2637. return
  2638. }
  2639. result = fmt.Sprintf("%g", math.Sqrt(number*math.Pi))
  2640. return
  2641. }
  2642. // SUM function adds together a supplied set of numbers and returns the sum of
  2643. // these values. The syntax of the function is:
  2644. //
  2645. // SUM(number1,[number2],...)
  2646. //
  2647. func (fn *formulaFuncs) SUM(argsList *list.List) (result string, err error) {
  2648. var val, sum float64
  2649. for arg := argsList.Front(); arg != nil; arg = arg.Next() {
  2650. token := arg.Value.(formulaArg)
  2651. switch token.Type {
  2652. case ArgUnknown:
  2653. continue
  2654. case ArgString:
  2655. if token.String == "" {
  2656. continue
  2657. }
  2658. if val, err = strconv.ParseFloat(token.String, 64); err != nil {
  2659. err = errors.New(formulaErrorVALUE)
  2660. return
  2661. }
  2662. sum += val
  2663. case ArgMatrix:
  2664. for _, row := range token.Matrix {
  2665. for _, value := range row {
  2666. if value.String == "" {
  2667. continue
  2668. }
  2669. if val, err = strconv.ParseFloat(value.String, 64); err != nil {
  2670. err = errors.New(formulaErrorVALUE)
  2671. return
  2672. }
  2673. sum += val
  2674. }
  2675. }
  2676. }
  2677. }
  2678. result = fmt.Sprintf("%g", sum)
  2679. return
  2680. }
  2681. // SUMIF function finds the values in a supplied array, that satisfy a given
  2682. // criteria, and returns the sum of the corresponding values in a second
  2683. // supplied array. The syntax of the function is:
  2684. //
  2685. // SUMIF(range,criteria,[sum_range])
  2686. //
  2687. func (fn *formulaFuncs) SUMIF(argsList *list.List) (result string, err error) {
  2688. if argsList.Len() < 2 {
  2689. err = errors.New("SUMIF requires at least 2 argument")
  2690. return
  2691. }
  2692. var criteria = formulaCriteriaParser(argsList.Front().Next().Value.(formulaArg).String)
  2693. var rangeMtx = argsList.Front().Value.(formulaArg).Matrix
  2694. var sumRange [][]formulaArg
  2695. if argsList.Len() == 3 {
  2696. sumRange = argsList.Back().Value.(formulaArg).Matrix
  2697. }
  2698. var sum, val float64
  2699. for rowIdx, row := range rangeMtx {
  2700. for colIdx, col := range row {
  2701. var ok bool
  2702. fromVal := col.String
  2703. if col.String == "" {
  2704. continue
  2705. }
  2706. if ok, err = formulaCriteriaEval(fromVal, criteria); err != nil {
  2707. return
  2708. }
  2709. if ok {
  2710. if argsList.Len() == 3 {
  2711. if len(sumRange) <= rowIdx || len(sumRange[rowIdx]) <= colIdx {
  2712. continue
  2713. }
  2714. fromVal = sumRange[rowIdx][colIdx].String
  2715. }
  2716. if val, err = strconv.ParseFloat(fromVal, 64); err != nil {
  2717. err = errors.New(formulaErrorVALUE)
  2718. return
  2719. }
  2720. sum += val
  2721. }
  2722. }
  2723. }
  2724. result = fmt.Sprintf("%g", sum)
  2725. return
  2726. }
  2727. // SUMSQ function returns the sum of squares of a supplied set of values. The
  2728. // syntax of the function is:
  2729. //
  2730. // SUMSQ(number1,[number2],...)
  2731. //
  2732. func (fn *formulaFuncs) SUMSQ(argsList *list.List) (result string, err error) {
  2733. var val, sq float64
  2734. for arg := argsList.Front(); arg != nil; arg = arg.Next() {
  2735. token := arg.Value.(formulaArg)
  2736. switch token.Type {
  2737. case ArgString:
  2738. if token.String == "" {
  2739. continue
  2740. }
  2741. if val, err = strconv.ParseFloat(token.String, 64); err != nil {
  2742. err = errors.New(formulaErrorVALUE)
  2743. return
  2744. }
  2745. sq += val * val
  2746. case ArgMatrix:
  2747. for _, row := range token.Matrix {
  2748. for _, value := range row {
  2749. if value.String == "" {
  2750. continue
  2751. }
  2752. if val, err = strconv.ParseFloat(value.String, 64); err != nil {
  2753. err = errors.New(formulaErrorVALUE)
  2754. return
  2755. }
  2756. sq += val * val
  2757. }
  2758. }
  2759. }
  2760. }
  2761. result = fmt.Sprintf("%g", sq)
  2762. return
  2763. }
  2764. // TAN function calculates the tangent of a given angle. The syntax of the
  2765. // function is:
  2766. //
  2767. // TAN(number)
  2768. //
  2769. func (fn *formulaFuncs) TAN(argsList *list.List) (result string, err error) {
  2770. if argsList.Len() != 1 {
  2771. err = errors.New("TAN requires 1 numeric argument")
  2772. return
  2773. }
  2774. var number float64
  2775. if number, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).String, 64); err != nil {
  2776. err = errors.New(formulaErrorVALUE)
  2777. return
  2778. }
  2779. result = fmt.Sprintf("%g", math.Tan(number))
  2780. return
  2781. }
  2782. // TANH function calculates the hyperbolic tangent (tanh) of a supplied
  2783. // number. The syntax of the function is:
  2784. //
  2785. // TANH(number)
  2786. //
  2787. func (fn *formulaFuncs) TANH(argsList *list.List) (result string, err error) {
  2788. if argsList.Len() != 1 {
  2789. err = errors.New("TANH requires 1 numeric argument")
  2790. return
  2791. }
  2792. var number float64
  2793. if number, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).String, 64); err != nil {
  2794. err = errors.New(formulaErrorVALUE)
  2795. return
  2796. }
  2797. result = fmt.Sprintf("%g", math.Tanh(number))
  2798. return
  2799. }
  2800. // TRUNC function truncates a supplied number to a specified number of decimal
  2801. // places. The syntax of the function is:
  2802. //
  2803. // TRUNC(number,[number_digits])
  2804. //
  2805. func (fn *formulaFuncs) TRUNC(argsList *list.List) (result string, err error) {
  2806. if argsList.Len() == 0 {
  2807. err = errors.New("TRUNC requires at least 1 argument")
  2808. return
  2809. }
  2810. var number, digits, adjust, rtrim float64
  2811. if number, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).String, 64); err != nil {
  2812. err = errors.New(formulaErrorVALUE)
  2813. return
  2814. }
  2815. if argsList.Len() > 1 {
  2816. if digits, err = strconv.ParseFloat(argsList.Back().Value.(formulaArg).String, 64); err != nil {
  2817. err = errors.New(formulaErrorVALUE)
  2818. return
  2819. }
  2820. digits = math.Floor(digits)
  2821. }
  2822. adjust = math.Pow(10, digits)
  2823. x := int((math.Abs(number) - math.Abs(float64(int(number)))) * adjust)
  2824. if x != 0 {
  2825. if rtrim, err = strconv.ParseFloat(strings.TrimRight(strconv.Itoa(x), "0"), 64); err != nil {
  2826. return
  2827. }
  2828. }
  2829. if (digits > 0) && (rtrim < adjust/10) {
  2830. result = fmt.Sprintf("%g", number)
  2831. return
  2832. }
  2833. result = fmt.Sprintf("%g", float64(int(number*adjust))/adjust)
  2834. return
  2835. }
  2836. // Statistical functions
  2837. // COUNTA function returns the number of non-blanks within a supplied set of
  2838. // cells or values. The syntax of the function is:
  2839. //
  2840. // COUNTA(value1,[value2],...)
  2841. //
  2842. func (fn *formulaFuncs) COUNTA(argsList *list.List) (result string, err error) {
  2843. var count int
  2844. for token := argsList.Front(); token != nil; token = token.Next() {
  2845. arg := token.Value.(formulaArg)
  2846. switch arg.Type {
  2847. case ArgString:
  2848. if arg.String != "" {
  2849. count++
  2850. }
  2851. case ArgMatrix:
  2852. for _, row := range arg.Matrix {
  2853. for _, value := range row {
  2854. if value.String != "" {
  2855. count++
  2856. }
  2857. }
  2858. }
  2859. }
  2860. }
  2861. result = fmt.Sprintf("%d", count)
  2862. return
  2863. }
  2864. // MEDIAN function returns the statistical median (the middle value) of a list
  2865. // of supplied numbers. The syntax of the function is:
  2866. //
  2867. // MEDIAN(number1,[number2],...)
  2868. //
  2869. func (fn *formulaFuncs) MEDIAN(argsList *list.List) (result string, err error) {
  2870. if argsList.Len() == 0 {
  2871. err = errors.New("MEDIAN requires at least 1 argument")
  2872. return
  2873. }
  2874. values := []float64{}
  2875. var median, digits float64
  2876. for token := argsList.Front(); token != nil; token = token.Next() {
  2877. arg := token.Value.(formulaArg)
  2878. switch arg.Type {
  2879. case ArgString:
  2880. if digits, err = strconv.ParseFloat(argsList.Back().Value.(formulaArg).String, 64); err != nil {
  2881. err = errors.New(formulaErrorVALUE)
  2882. return
  2883. }
  2884. values = append(values, digits)
  2885. case ArgMatrix:
  2886. for _, row := range arg.Matrix {
  2887. for _, value := range row {
  2888. if value.String == "" {
  2889. continue
  2890. }
  2891. if digits, err = strconv.ParseFloat(value.String, 64); err != nil {
  2892. err = errors.New(formulaErrorVALUE)
  2893. return
  2894. }
  2895. values = append(values, digits)
  2896. }
  2897. }
  2898. }
  2899. }
  2900. sort.Float64s(values)
  2901. if len(values)%2 == 0 {
  2902. median = (values[len(values)/2-1] + values[len(values)/2]) / 2
  2903. } else {
  2904. median = values[len(values)/2]
  2905. }
  2906. result = fmt.Sprintf("%g", median)
  2907. return
  2908. }
  2909. // Information functions
  2910. // ISBLANK function tests if a specified cell is blank (empty) and if so,
  2911. // returns TRUE; Otherwise the function returns FALSE. The syntax of the
  2912. // function is:
  2913. //
  2914. // ISBLANK(value)
  2915. //
  2916. func (fn *formulaFuncs) ISBLANK(argsList *list.List) (result string, err error) {
  2917. if argsList.Len() != 1 {
  2918. err = errors.New("ISBLANK requires 1 argument")
  2919. return
  2920. }
  2921. token := argsList.Front().Value.(formulaArg)
  2922. result = "FALSE"
  2923. switch token.Type {
  2924. case ArgUnknown:
  2925. result = "TRUE"
  2926. case ArgString:
  2927. if token.String == "" {
  2928. result = "TRUE"
  2929. }
  2930. }
  2931. return
  2932. }
  2933. // ISERR function tests if an initial supplied expression (or value) returns
  2934. // any Excel Error, except the #N/A error. If so, the function returns the
  2935. // logical value TRUE; If the supplied value is not an error or is the #N/A
  2936. // error, the ISERR function returns FALSE. The syntax of the function is:
  2937. //
  2938. // ISERR(value)
  2939. //
  2940. func (fn *formulaFuncs) ISERR(argsList *list.List) (result string, err error) {
  2941. if argsList.Len() != 1 {
  2942. err = errors.New("ISERR requires 1 argument")
  2943. return
  2944. }
  2945. token := argsList.Front().Value.(formulaArg)
  2946. result = "FALSE"
  2947. if token.Type == ArgString {
  2948. for _, errType := range []string{formulaErrorDIV, formulaErrorNAME, formulaErrorNUM, formulaErrorVALUE, formulaErrorREF, formulaErrorNULL, formulaErrorSPILL, formulaErrorCALC, formulaErrorGETTINGDATA} {
  2949. if errType == token.String {
  2950. result = "TRUE"
  2951. }
  2952. }
  2953. }
  2954. return
  2955. }
  2956. // ISERROR function tests if an initial supplied expression (or value) returns
  2957. // an Excel Error, and if so, returns the logical value TRUE; Otherwise the
  2958. // function returns FALSE. The syntax of the function is:
  2959. //
  2960. // ISERROR(value)
  2961. //
  2962. func (fn *formulaFuncs) ISERROR(argsList *list.List) (result string, err error) {
  2963. if argsList.Len() != 1 {
  2964. err = errors.New("ISERROR requires 1 argument")
  2965. return
  2966. }
  2967. token := argsList.Front().Value.(formulaArg)
  2968. result = "FALSE"
  2969. if token.Type == ArgString {
  2970. for _, errType := range []string{formulaErrorDIV, formulaErrorNAME, formulaErrorNA, formulaErrorNUM, formulaErrorVALUE, formulaErrorREF, formulaErrorNULL, formulaErrorSPILL, formulaErrorCALC, formulaErrorGETTINGDATA} {
  2971. if errType == token.String {
  2972. result = "TRUE"
  2973. }
  2974. }
  2975. }
  2976. return
  2977. }
  2978. // ISEVEN function tests if a supplied number (or numeric expression)
  2979. // evaluates to an even number, and if so, returns TRUE; Otherwise, the
  2980. // function returns FALSE. The syntax of the function is:
  2981. //
  2982. // ISEVEN(value)
  2983. //
  2984. func (fn *formulaFuncs) ISEVEN(argsList *list.List) (result string, err error) {
  2985. if argsList.Len() != 1 {
  2986. err = errors.New("ISEVEN requires 1 argument")
  2987. return
  2988. }
  2989. token := argsList.Front().Value.(formulaArg)
  2990. result = "FALSE"
  2991. var numeric int
  2992. if token.Type == ArgString {
  2993. if numeric, err = strconv.Atoi(token.String); err != nil {
  2994. err = errors.New(formulaErrorVALUE)
  2995. return
  2996. }
  2997. if numeric == numeric/2*2 {
  2998. result = "TRUE"
  2999. return
  3000. }
  3001. }
  3002. return
  3003. }
  3004. // ISNA function tests if an initial supplied expression (or value) returns
  3005. // the Excel #N/A Error, and if so, returns TRUE; Otherwise the function
  3006. // returns FALSE. The syntax of the function is:
  3007. //
  3008. // ISNA(value)
  3009. //
  3010. func (fn *formulaFuncs) ISNA(argsList *list.List) (result string, err error) {
  3011. if argsList.Len() != 1 {
  3012. err = errors.New("ISNA requires 1 argument")
  3013. return
  3014. }
  3015. token := argsList.Front().Value.(formulaArg)
  3016. result = "FALSE"
  3017. if token.Type == ArgString && token.String == formulaErrorNA {
  3018. result = "TRUE"
  3019. }
  3020. return
  3021. }
  3022. // ISNONTEXT function function tests if a supplied value is text. If not, the
  3023. // function returns TRUE; If the supplied value is text, the function returns
  3024. // FALSE. The syntax of the function is:
  3025. //
  3026. // ISNONTEXT(value)
  3027. //
  3028. func (fn *formulaFuncs) ISNONTEXT(argsList *list.List) (result string, err error) {
  3029. if argsList.Len() != 1 {
  3030. err = errors.New("ISNONTEXT requires 1 argument")
  3031. return
  3032. }
  3033. token := argsList.Front().Value.(formulaArg)
  3034. result = "TRUE"
  3035. if token.Type == ArgString && token.String != "" {
  3036. result = "FALSE"
  3037. }
  3038. return
  3039. }
  3040. // ISNUMBER function function tests if a supplied value is a number. If so,
  3041. // the function returns TRUE; Otherwise it returns FALSE. The syntax of the
  3042. // function is:
  3043. //
  3044. // ISNUMBER(value)
  3045. //
  3046. func (fn *formulaFuncs) ISNUMBER(argsList *list.List) (result string, err error) {
  3047. if argsList.Len() != 1 {
  3048. err = errors.New("ISNUMBER requires 1 argument")
  3049. return
  3050. }
  3051. token := argsList.Front().Value.(formulaArg)
  3052. result = "FALSE"
  3053. if token.Type == ArgString && token.String != "" {
  3054. if _, err = strconv.Atoi(token.String); err == nil {
  3055. result = "TRUE"
  3056. }
  3057. err = nil
  3058. }
  3059. return
  3060. }
  3061. // ISODD function tests if a supplied number (or numeric expression) evaluates
  3062. // to an odd number, and if so, returns TRUE; Otherwise, the function returns
  3063. // FALSE. The syntax of the function is:
  3064. //
  3065. // ISODD(value)
  3066. //
  3067. func (fn *formulaFuncs) ISODD(argsList *list.List) (result string, err error) {
  3068. if argsList.Len() != 1 {
  3069. err = errors.New("ISODD requires 1 argument")
  3070. return
  3071. }
  3072. token := argsList.Front().Value.(formulaArg)
  3073. result = "FALSE"
  3074. var numeric int
  3075. if token.Type == ArgString {
  3076. if numeric, err = strconv.Atoi(token.String); err != nil {
  3077. err = errors.New(formulaErrorVALUE)
  3078. return
  3079. }
  3080. if numeric != numeric/2*2 {
  3081. result = "TRUE"
  3082. return
  3083. }
  3084. }
  3085. return
  3086. }
  3087. // NA function returns the Excel #N/A error. This error message has the
  3088. // meaning 'value not available' and is produced when an Excel Formula is
  3089. // unable to find a value that it needs. The syntax of the function is:
  3090. //
  3091. // NA()
  3092. //
  3093. func (fn *formulaFuncs) NA(argsList *list.List) (result string, err error) {
  3094. if argsList.Len() != 0 {
  3095. err = errors.New("NA accepts no arguments")
  3096. return
  3097. }
  3098. result = formulaErrorNA
  3099. return
  3100. }
  3101. // Logical Functions
  3102. // AND function tests a number of supplied conditions and returns TRUE or
  3103. // FALSE. The syntax of the function is:
  3104. //
  3105. // AND(logical_test1,[logical_test2],...)
  3106. //
  3107. func (fn *formulaFuncs) AND(argsList *list.List) (result string, err error) {
  3108. if argsList.Len() == 0 {
  3109. err = errors.New("AND requires at least 1 argument")
  3110. return
  3111. }
  3112. if argsList.Len() > 30 {
  3113. err = errors.New("AND accepts at most 30 arguments")
  3114. return
  3115. }
  3116. var and = true
  3117. var val float64
  3118. for arg := argsList.Front(); arg != nil; arg = arg.Next() {
  3119. token := arg.Value.(formulaArg)
  3120. switch token.Type {
  3121. case ArgUnknown:
  3122. continue
  3123. case ArgString:
  3124. if token.String == "TRUE" {
  3125. continue
  3126. }
  3127. if token.String == "FALSE" {
  3128. result = token.String
  3129. return
  3130. }
  3131. if val, err = strconv.ParseFloat(token.String, 64); err != nil {
  3132. err = errors.New(formulaErrorVALUE)
  3133. return
  3134. }
  3135. and = and && (val != 0)
  3136. case ArgMatrix:
  3137. // TODO
  3138. err = errors.New(formulaErrorVALUE)
  3139. return
  3140. }
  3141. }
  3142. result = strings.ToUpper(strconv.FormatBool(and))
  3143. return
  3144. }
  3145. // OR function tests a number of supplied conditions and returns either TRUE
  3146. // or FALSE. The syntax of the function is:
  3147. //
  3148. // OR(logical_test1,[logical_test2],...)
  3149. //
  3150. func (fn *formulaFuncs) OR(argsList *list.List) (result string, err error) {
  3151. if argsList.Len() == 0 {
  3152. err = errors.New("OR requires at least 1 argument")
  3153. return
  3154. }
  3155. if argsList.Len() > 30 {
  3156. err = errors.New("OR accepts at most 30 arguments")
  3157. return
  3158. }
  3159. var or bool
  3160. var val float64
  3161. for arg := argsList.Front(); arg != nil; arg = arg.Next() {
  3162. token := arg.Value.(formulaArg)
  3163. switch token.Type {
  3164. case ArgUnknown:
  3165. continue
  3166. case ArgString:
  3167. if token.String == "FALSE" {
  3168. continue
  3169. }
  3170. if token.String == "TRUE" {
  3171. or = true
  3172. continue
  3173. }
  3174. if val, err = strconv.ParseFloat(token.String, 64); err != nil {
  3175. err = errors.New(formulaErrorVALUE)
  3176. return
  3177. }
  3178. or = val != 0
  3179. case ArgMatrix:
  3180. // TODO
  3181. err = errors.New(formulaErrorVALUE)
  3182. return
  3183. }
  3184. }
  3185. result = strings.ToUpper(strconv.FormatBool(or))
  3186. return
  3187. }
  3188. // Date and Time Functions
  3189. // DATE returns a date, from a user-supplied year, month and day. The syntax
  3190. // of the function is:
  3191. //
  3192. // DATE(year,month,day)
  3193. //
  3194. func (fn *formulaFuncs) DATE(argsList *list.List) (result string, err error) {
  3195. if argsList.Len() != 3 {
  3196. err = errors.New("DATE requires 3 number arguments")
  3197. return
  3198. }
  3199. var year, month, day int
  3200. if year, err = strconv.Atoi(argsList.Front().Value.(formulaArg).String); err != nil {
  3201. err = errors.New("DATE requires 3 number arguments")
  3202. return
  3203. }
  3204. if month, err = strconv.Atoi(argsList.Front().Next().Value.(formulaArg).String); err != nil {
  3205. err = errors.New("DATE requires 3 number arguments")
  3206. return
  3207. }
  3208. if day, err = strconv.Atoi(argsList.Back().Value.(formulaArg).String); err != nil {
  3209. err = errors.New("DATE requires 3 number arguments")
  3210. return
  3211. }
  3212. d := makeDate(year, time.Month(month), day)
  3213. result = timeFromExcelTime(daysBetween(excelMinTime1900.Unix(), d)+1, false).String()
  3214. return
  3215. }
  3216. // makeDate return date as a Unix time, the number of seconds elapsed since
  3217. // January 1, 1970 UTC.
  3218. func makeDate(y int, m time.Month, d int) int64 {
  3219. if y == 1900 && int(m) <= 2 {
  3220. d--
  3221. }
  3222. date := time.Date(y, m, d, 0, 0, 0, 0, time.UTC)
  3223. return date.Unix()
  3224. }
  3225. // daysBetween return time interval of the given start timestamp and end
  3226. // timestamp.
  3227. func daysBetween(startDate, endDate int64) float64 {
  3228. return float64(int(0.5 + float64((endDate-startDate)/86400)))
  3229. }
  3230. // Text Functions
  3231. // CLEAN removes all non-printable characters from a supplied text string. The
  3232. // syntax of the function is:
  3233. //
  3234. // CLEAN(text)
  3235. //
  3236. func (fn *formulaFuncs) CLEAN(argsList *list.List) (result string, err error) {
  3237. if argsList.Len() != 1 {
  3238. err = errors.New("CLEAN requires 1 argument")
  3239. return
  3240. }
  3241. b := bytes.Buffer{}
  3242. for _, c := range argsList.Front().Value.(formulaArg).String {
  3243. if c > 31 {
  3244. b.WriteRune(c)
  3245. }
  3246. }
  3247. result = b.String()
  3248. return
  3249. }
  3250. // TRIM removes extra spaces (i.e. all spaces except for single spaces between
  3251. // words or characters) from a supplied text string. The syntax of the
  3252. // function is:
  3253. //
  3254. // TRIM(text)
  3255. //
  3256. func (fn *formulaFuncs) TRIM(argsList *list.List) (result string, err error) {
  3257. if argsList.Len() != 1 {
  3258. err = errors.New("TRIM requires 1 argument")
  3259. return
  3260. }
  3261. result = strings.TrimSpace(argsList.Front().Value.(formulaArg).String)
  3262. return
  3263. }
  3264. // LOWER converts all characters in a supplied text string to lower case. The
  3265. // syntax of the function is:
  3266. //
  3267. // LOWER(text)
  3268. //
  3269. func (fn *formulaFuncs) LOWER(argsList *list.List) (result string, err error) {
  3270. if argsList.Len() != 1 {
  3271. err = errors.New("LOWER requires 1 argument")
  3272. return
  3273. }
  3274. result = strings.ToLower(argsList.Front().Value.(formulaArg).String)
  3275. return
  3276. }
  3277. // PROPER converts all characters in a supplied text string to proper case
  3278. // (i.e. all letters that do not immediately follow another letter are set to
  3279. // upper case and all other characters are lower case). The syntax of the
  3280. // function is:
  3281. //
  3282. // PROPER(text)
  3283. //
  3284. func (fn *formulaFuncs) PROPER(argsList *list.List) (result string, err error) {
  3285. if argsList.Len() != 1 {
  3286. err = errors.New("PROPER requires 1 argument")
  3287. return
  3288. }
  3289. buf := bytes.Buffer{}
  3290. isLetter := false
  3291. for _, char := range argsList.Front().Value.(formulaArg).String {
  3292. if !isLetter && unicode.IsLetter(char) {
  3293. buf.WriteRune(unicode.ToUpper(char))
  3294. } else {
  3295. buf.WriteRune(unicode.ToLower(char))
  3296. }
  3297. isLetter = unicode.IsLetter(char)
  3298. }
  3299. result = buf.String()
  3300. return
  3301. }
  3302. // UPPER converts all characters in a supplied text string to upper case. The
  3303. // syntax of the function is:
  3304. //
  3305. // UPPER(text)
  3306. //
  3307. func (fn *formulaFuncs) UPPER(argsList *list.List) (result string, err error) {
  3308. if argsList.Len() != 1 {
  3309. err = errors.New("UPPER requires 1 argument")
  3310. return
  3311. }
  3312. result = strings.ToUpper(argsList.Front().Value.(formulaArg).String)
  3313. return
  3314. }