decimal_test.go 79 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808
  1. package decimal
  2. import (
  3. "database/sql/driver"
  4. "encoding/json"
  5. "encoding/xml"
  6. "fmt"
  7. "math"
  8. "math/big"
  9. "math/rand"
  10. "reflect"
  11. "regexp"
  12. "strconv"
  13. "strings"
  14. "testing"
  15. "testing/quick"
  16. "time"
  17. )
  18. type testEnt struct {
  19. float float64
  20. short string
  21. exact string
  22. inexact string
  23. }
  24. var testTable = []*testEnt{
  25. {3.141592653589793, "3.141592653589793", "", "3.14159265358979300000000000000000000000000000000000004"},
  26. {3, "3", "", "3.0000000000000000000000002"},
  27. {1234567890123456, "1234567890123456", "", "1234567890123456.00000000000000002"},
  28. {1234567890123456000, "1234567890123456000", "", "1234567890123456000.0000000000000008"},
  29. {1234.567890123456, "1234.567890123456", "", "1234.5678901234560000000000000009"},
  30. {.1234567890123456, "0.1234567890123456", "", "0.12345678901234560000000000006"},
  31. {0, "0", "", "0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001"},
  32. {.1111111111111110, "0.111111111111111", "", "0.111111111111111000000000000000009"},
  33. {.1111111111111111, "0.1111111111111111", "", "0.111111111111111100000000000000000000023423545644534234"},
  34. {.1111111111111119, "0.1111111111111119", "", "0.111111111111111900000000000000000000000000000000000134123984192834"},
  35. {.000000000000000001, "0.000000000000000001", "", "0.00000000000000000100000000000000000000000000000000012341234"},
  36. {.000000000000000002, "0.000000000000000002", "", "0.0000000000000000020000000000000000000012341234123"},
  37. {.000000000000000003, "0.000000000000000003", "", "0.00000000000000000299999999999999999999999900000000000123412341234"},
  38. {.000000000000000005, "0.000000000000000005", "", "0.00000000000000000500000000000000000023412341234"},
  39. {.000000000000000008, "0.000000000000000008", "", "0.0000000000000000080000000000000000001241234432"},
  40. {.1000000000000001, "0.1000000000000001", "", "0.10000000000000010000000000000012341234"},
  41. {.1000000000000002, "0.1000000000000002", "", "0.10000000000000020000000000001234123412"},
  42. {.1000000000000003, "0.1000000000000003", "", "0.1000000000000003000000000000001234123412"},
  43. {.1000000000000005, "0.1000000000000005", "", "0.1000000000000005000000000000000006441234"},
  44. {.1000000000000008, "0.1000000000000008", "", "0.100000000000000800000000000000000009999999999999999999999999999"},
  45. {1e25, "10000000000000000000000000", "", ""},
  46. {1.5e14, "150000000000000", "", ""},
  47. {1.5e15, "1500000000000000", "", ""},
  48. {1.5e16, "15000000000000000", "", ""},
  49. {1.0001e25, "10001000000000000000000000", "", ""},
  50. {1.0001000000000000033e25, "10001000000000000000000000", "", ""},
  51. {2e25, "20000000000000000000000000", "", ""},
  52. {4e25, "40000000000000000000000000", "", ""},
  53. {8e25, "80000000000000000000000000", "", ""},
  54. {1e250, "10000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", "", ""},
  55. {2e250, "20000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", "", ""},
  56. {math.MaxInt64, strconv.FormatFloat(float64(math.MaxInt64), 'f', -1, 64), "", strconv.FormatInt(math.MaxInt64, 10)},
  57. {1.29067116156722e-309, "0.00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000129067116156722", "", "0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001290671161567218558822290567835270536800098852722416870074139002112543896676308448335063375297788379444685193974290737962187240854947838776604607190387984577130572928111657710645015086812756013489109884753559084166516937690932698276436869274093950997935137476803610007959500457935217950764794724766740819156974617155861568214427828145972181876775307023388139991104942469299524961281641158436752347582767153796914843896176260096039358494077706152272661453132497761307744086665088096215425146090058519888494342944692629602847826300550628670375451325582843627504604013541465361435761965354140678551369499812124085312128659002910905639984075064968459581691226705666561364681985266583563078466180095375402399087817404368974165082030458595596655868575908243656158447265625000000000000000000000000000000000000004440000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"},
  58. // go Issue 29491.
  59. {498484681984085570, "498484681984085570", "", ""},
  60. {5.8339553793802237e+23, "583395537938022370000000", "", ""},
  61. }
  62. var testTableScientificNotation = map[string]string{
  63. "1e9": "1000000000",
  64. "2.41E-3": "0.00241",
  65. "24.2E-4": "0.00242",
  66. "243E-5": "0.00243",
  67. "1e-5": "0.00001",
  68. "245E3": "245000",
  69. "1.2345E-1": "0.12345",
  70. "0e5": "0",
  71. "0e-5": "0",
  72. "0.e0": "0",
  73. ".0e0": "0",
  74. "123.456e0": "123.456",
  75. "123.456e2": "12345.6",
  76. "123.456e10": "1234560000000",
  77. }
  78. func init() {
  79. for _, s := range testTable {
  80. s.exact = strconv.FormatFloat(s.float, 'f', 1500, 64)
  81. if strings.ContainsRune(s.exact, '.') {
  82. s.exact = strings.TrimRight(s.exact, "0")
  83. s.exact = strings.TrimRight(s.exact, ".")
  84. }
  85. }
  86. // add negatives
  87. withNeg := testTable[:]
  88. for _, s := range testTable {
  89. if s.float > 0 && s.short != "0" && s.exact != "0" {
  90. withNeg = append(withNeg, &testEnt{-s.float, "-" + s.short, "-" + s.exact, "-" + s.inexact})
  91. }
  92. }
  93. testTable = withNeg
  94. for e, s := range testTableScientificNotation {
  95. if string(e[0]) != "-" && s != "0" {
  96. testTableScientificNotation["-"+e] = "-" + s
  97. }
  98. }
  99. }
  100. func TestNewFromFloat(t *testing.T) {
  101. for _, x := range testTable {
  102. s := x.short
  103. d := NewFromFloat(x.float)
  104. if d.String() != s {
  105. t.Errorf("expected %s, got %s (float: %v) (%s, %d)",
  106. s, d.String(), x.float,
  107. d.value.String(), d.exp)
  108. }
  109. }
  110. shouldPanicOn := []float64{
  111. math.NaN(),
  112. math.Inf(1),
  113. math.Inf(-1),
  114. }
  115. for _, n := range shouldPanicOn {
  116. var d Decimal
  117. if !didPanic(func() { d = NewFromFloat(n) }) {
  118. t.Fatalf("Expected panic when creating a Decimal from %v, got %v instead", n, d.String())
  119. }
  120. }
  121. }
  122. func TestNewFromFloatRandom(t *testing.T) {
  123. n := 0
  124. rng := rand.New(rand.NewSource(0xdead1337))
  125. for {
  126. n++
  127. if n == 10 {
  128. break
  129. }
  130. in := (rng.Float64() - 0.5) * math.MaxFloat64 * 2
  131. want, err := NewFromString(strconv.FormatFloat(in, 'f', -1, 64))
  132. if err != nil {
  133. t.Error(err)
  134. continue
  135. }
  136. got := NewFromFloat(in)
  137. if !want.Equal(got) {
  138. t.Errorf("in: %v, expected %s (%s, %d), got %s (%s, %d) ",
  139. in, want.String(), want.value.String(), want.exp,
  140. got.String(), got.value.String(), got.exp)
  141. }
  142. }
  143. }
  144. func TestNewFromFloatQuick(t *testing.T) {
  145. err := quick.Check(func(f float64) bool {
  146. want, werr := NewFromString(strconv.FormatFloat(f, 'f', -1, 64))
  147. if werr != nil {
  148. return true
  149. }
  150. got := NewFromFloat(f)
  151. return got.Equal(want)
  152. }, &quick.Config{})
  153. if err != nil {
  154. t.Error(err)
  155. }
  156. }
  157. func TestNewFromFloat32Random(t *testing.T) {
  158. n := 0
  159. rng := rand.New(rand.NewSource(0xdead1337))
  160. for {
  161. n++
  162. if n == 10 {
  163. break
  164. }
  165. in := float32((rng.Float64() - 0.5) * math.MaxFloat32 * 2)
  166. want, err := NewFromString(strconv.FormatFloat(float64(in), 'f', -1, 32))
  167. if err != nil {
  168. t.Error(err)
  169. continue
  170. }
  171. got := NewFromFloat32(in)
  172. if !want.Equal(got) {
  173. t.Errorf("in: %v, expected %s (%s, %d), got %s (%s, %d) ",
  174. in, want.String(), want.value.String(), want.exp,
  175. got.String(), got.value.String(), got.exp)
  176. }
  177. }
  178. }
  179. func TestNewFromFloat32Quick(t *testing.T) {
  180. err := quick.Check(func(f float32) bool {
  181. want, werr := NewFromString(strconv.FormatFloat(float64(f), 'f', -1, 32))
  182. if werr != nil {
  183. return true
  184. }
  185. got := NewFromFloat32(f)
  186. return got.Equal(want)
  187. }, &quick.Config{})
  188. if err != nil {
  189. t.Error(err)
  190. }
  191. }
  192. func TestNewFromString(t *testing.T) {
  193. for _, x := range testTable {
  194. s := x.short
  195. d, err := NewFromString(s)
  196. if err != nil {
  197. t.Errorf("error while parsing %s", s)
  198. } else if d.String() != s {
  199. t.Errorf("expected %s, got %s (%s, %d)",
  200. s, d.String(),
  201. d.value.String(), d.exp)
  202. }
  203. }
  204. for _, x := range testTable {
  205. s := x.exact
  206. d, err := NewFromString(s)
  207. if err != nil {
  208. t.Errorf("error while parsing %s", s)
  209. } else if d.String() != s {
  210. t.Errorf("expected %s, got %s (%s, %d)",
  211. s, d.String(),
  212. d.value.String(), d.exp)
  213. }
  214. }
  215. for e, s := range testTableScientificNotation {
  216. d, err := NewFromString(e)
  217. if err != nil {
  218. t.Errorf("error while parsing %s", e)
  219. } else if d.String() != s {
  220. t.Errorf("expected %s, got %s (%s, %d)",
  221. s, d.String(),
  222. d.value.String(), d.exp)
  223. }
  224. }
  225. }
  226. func TestNewFromFormattedString(t *testing.T) {
  227. for _, testCase := range []struct {
  228. Formatted string
  229. Expected string
  230. ReplRegex *regexp.Regexp
  231. }{
  232. {"$10.99", "10.99", regexp.MustCompile("[$]")},
  233. {"$ 12.1", "12.1", regexp.MustCompile("[$\\s]")},
  234. {"$61,690.99", "61690.99", regexp.MustCompile("[$,]")},
  235. {"1_000_000.00", "1000000.00", regexp.MustCompile("[_]")},
  236. {"41,410.00", "41410.00", regexp.MustCompile("[,]")},
  237. {"5200 USD", "5200", regexp.MustCompile("[USD\\s]")},
  238. } {
  239. dFormatted, err := NewFromFormattedString(testCase.Formatted, testCase.ReplRegex)
  240. if err != nil {
  241. t.Fatal(err)
  242. }
  243. dExact, err := NewFromString(testCase.Expected)
  244. if err != nil {
  245. t.Fatal(err)
  246. }
  247. if !dFormatted.Equal(dExact) {
  248. t.Errorf("expect %s, got %s", dExact, dFormatted)
  249. }
  250. }
  251. }
  252. func TestFloat64(t *testing.T) {
  253. for _, x := range testTable {
  254. if x.inexact == "" || x.inexact == "-" {
  255. continue
  256. }
  257. s := x.exact
  258. d, err := NewFromString(s)
  259. if err != nil {
  260. t.Errorf("error while parsing %s", s)
  261. } else if f, exact := d.Float64(); !exact || f != x.float {
  262. t.Errorf("cannot represent exactly %s", s)
  263. }
  264. s = x.inexact
  265. d, err = NewFromString(s)
  266. if err != nil {
  267. t.Errorf("error while parsing %s", s)
  268. } else if f, exact := d.Float64(); exact || f != x.float {
  269. t.Errorf("%s should be represented inexactly", s)
  270. }
  271. }
  272. }
  273. func TestNewFromStringErrs(t *testing.T) {
  274. tests := []string{
  275. "",
  276. "qwert",
  277. "-",
  278. ".",
  279. "-.",
  280. ".-",
  281. "234-.56",
  282. "234-56",
  283. "2-",
  284. "..",
  285. "2..",
  286. "..2",
  287. ".5.2",
  288. "8..2",
  289. "8.1.",
  290. "1e",
  291. "1-e",
  292. "1e9e",
  293. "1ee9",
  294. "1ee",
  295. "1eE",
  296. "1e-",
  297. "1e-.",
  298. "1e1.2",
  299. "123.456e1.3",
  300. "1e-1.2",
  301. "123.456e-1.3",
  302. "123.456Easdf",
  303. "123.456e" + strconv.FormatInt(math.MinInt64, 10),
  304. "123.456e" + strconv.FormatInt(math.MinInt32, 10),
  305. "512.99 USD",
  306. "$99.99",
  307. "51,850.00",
  308. "20_000_000.00",
  309. "$20_000_000.00",
  310. }
  311. for _, s := range tests {
  312. _, err := NewFromString(s)
  313. if err == nil {
  314. t.Errorf("error expected when parsing %s", s)
  315. }
  316. }
  317. }
  318. func TestNewFromStringDeepEquals(t *testing.T) {
  319. type StrCmp struct {
  320. str1 string
  321. str2 string
  322. expected bool
  323. }
  324. tests := []StrCmp{
  325. {"1", "1", true},
  326. {"1.0", "1.0", true},
  327. {"10", "10.0", false},
  328. {"1.1", "1.10", false},
  329. {"1.001", "1.01", false},
  330. }
  331. for _, cmp := range tests {
  332. d1, err1 := NewFromString(cmp.str1)
  333. d2, err2 := NewFromString(cmp.str2)
  334. if err1 != nil || err2 != nil {
  335. t.Errorf("error parsing strings to decimals")
  336. }
  337. if reflect.DeepEqual(d1, d2) != cmp.expected {
  338. t.Errorf("comparison result is different from expected results for %s and %s",
  339. cmp.str1, cmp.str2)
  340. }
  341. }
  342. }
  343. func TestRequireFromString(t *testing.T) {
  344. s := "1.23"
  345. defer func() {
  346. err := recover()
  347. if err != nil {
  348. t.Errorf("error while parsing %s", s)
  349. }
  350. }()
  351. d := RequireFromString(s)
  352. if d.String() != s {
  353. t.Errorf("expected %s, got %s (%s, %d)",
  354. s, d.String(),
  355. d.value.String(), d.exp)
  356. }
  357. }
  358. func TestRequireFromStringErrs(t *testing.T) {
  359. s := "qwert"
  360. var d Decimal
  361. var err interface{}
  362. func(d Decimal) {
  363. defer func() {
  364. err = recover()
  365. }()
  366. RequireFromString(s)
  367. }(d)
  368. if err == nil {
  369. t.Errorf("panic expected when parsing %s", s)
  370. }
  371. }
  372. func TestNewFromFloatWithExponent(t *testing.T) {
  373. type Inp struct {
  374. float float64
  375. exp int32
  376. }
  377. // some tests are taken from here https://www.cockroachlabs.com/blog/rounding-implementations-in-go/
  378. tests := map[Inp]string{
  379. Inp{123.4, -3}: "123.4",
  380. Inp{123.4, -1}: "123.4",
  381. Inp{123.412345, 1}: "120",
  382. Inp{123.412345, 0}: "123",
  383. Inp{123.412345, -5}: "123.41235",
  384. Inp{123.412345, -6}: "123.412345",
  385. Inp{123.412345, -7}: "123.412345",
  386. Inp{123.412345, -28}: "123.4123450000000019599610823207",
  387. Inp{1230000000, 3}: "1230000000",
  388. Inp{123.9999999999999999, -7}: "124",
  389. Inp{123.8989898999999999, -7}: "123.8989899",
  390. Inp{0.49999999999999994, 0}: "0",
  391. Inp{0.5, 0}: "1",
  392. Inp{0., -1000}: "0",
  393. Inp{0.5000000000000001, 0}: "1",
  394. Inp{1.390671161567e-309, 0}: "0",
  395. Inp{4.503599627370497e+15, 0}: "4503599627370497",
  396. Inp{4.503599627370497e+60, 0}: "4503599627370497110902645731364739935039854989106233267453952",
  397. Inp{4.503599627370497e+60, 1}: "4503599627370497110902645731364739935039854989106233267453950",
  398. Inp{4.503599627370497e+60, -1}: "4503599627370497110902645731364739935039854989106233267453952",
  399. Inp{50, 2}: "100",
  400. Inp{49, 2}: "0",
  401. Inp{50, 3}: "0",
  402. // subnormals
  403. Inp{1.390671161567e-309, -2000}: "0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001390671161567000864431395448332752540137009987788957394095829635554502771758698872408926974382819387852542087331897381878220271350970912568035007740861074263206736245957501456549756342151614772544950978154339064833880234531754156635411349342950306987480369774780312897442981323940546749863054846093718407237782253156822124910364044261653195961209878120072488178603782495270845071470243842997312255994555557251870400944414666445871039673491570643357351279578519863428540219295076767898526278029257129758694673164251056158277568765100904638511604478844087596428177947970563689475826736810456067108202083804368114484417399279328807983736233036662284338182105684628835292230438999173947056675615385756827890872955322265625",
  404. Inp{1.390671161567e-309, -862}: "0.0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000013906711615670008644313954483327525401370099877889573940958296355545027717586988724089269743828193878525420873318973818782202713509709125680350077408610742632067362459575014565497563421516147725449509781543390648338802345317541566354113493429503069874803697747803128974429813239405467498630548460937184072377822531568221249103640442616531959612098781200724881786037824952708450714702438429973122559945555572518704009444146664458710396734915706433573512795785198634285402192950767678985262780292571297586946731642510561582775687651009046385116044788440876",
  405. Inp{1.390671161567e-309, -863}: "0.0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000013906711615670008644313954483327525401370099877889573940958296355545027717586988724089269743828193878525420873318973818782202713509709125680350077408610742632067362459575014565497563421516147725449509781543390648338802345317541566354113493429503069874803697747803128974429813239405467498630548460937184072377822531568221249103640442616531959612098781200724881786037824952708450714702438429973122559945555572518704009444146664458710396734915706433573512795785198634285402192950767678985262780292571297586946731642510561582775687651009046385116044788440876",
  406. }
  407. // add negatives
  408. for p, s := range tests {
  409. if p.float > 0 {
  410. if s != "0" {
  411. tests[Inp{-p.float, p.exp}] = "-" + s
  412. } else {
  413. tests[Inp{-p.float, p.exp}] = "0"
  414. }
  415. }
  416. }
  417. for input, s := range tests {
  418. d := NewFromFloatWithExponent(input.float, input.exp)
  419. if d.String() != s {
  420. t.Errorf("expected %s, got %s (%s, %d)",
  421. s, d.String(),
  422. d.value.String(), d.exp)
  423. }
  424. }
  425. shouldPanicOn := []float64{
  426. math.NaN(),
  427. math.Inf(1),
  428. math.Inf(-1),
  429. }
  430. for _, n := range shouldPanicOn {
  431. var d Decimal
  432. if !didPanic(func() { d = NewFromFloatWithExponent(n, 0) }) {
  433. t.Fatalf("Expected panic when creating a Decimal from %v, got %v instead", n, d.String())
  434. }
  435. }
  436. }
  437. func TestNewFromInt(t *testing.T) {
  438. tests := map[int64]string{
  439. 0: "0",
  440. 1: "1",
  441. 323412345: "323412345",
  442. 9223372036854775807: "9223372036854775807",
  443. }
  444. // add negatives
  445. for p, s := range tests {
  446. if p > 0 {
  447. tests[-p] = "-" + s
  448. }
  449. }
  450. for input, s := range tests {
  451. d := NewFromInt(input)
  452. if d.String() != s {
  453. t.Errorf("expected %s, got %s (%s, %d)",
  454. s, d.String(),
  455. d.value.String(), d.exp)
  456. }
  457. }
  458. }
  459. func TestNewFromInt32(t *testing.T) {
  460. tests := map[int32]string{
  461. 0: "0",
  462. 1: "1",
  463. 323412345: "323412345",
  464. 2147483647: "2147483647",
  465. }
  466. // add negatives
  467. for p, s := range tests {
  468. if p > 0 {
  469. tests[-p] = "-" + s
  470. }
  471. }
  472. for input, s := range tests {
  473. d := NewFromInt32(input)
  474. if d.String() != s {
  475. t.Errorf("expected %s, got %s (%s, %d)",
  476. s, d.String(),
  477. d.value.String(), d.exp)
  478. }
  479. }
  480. }
  481. func TestNewFromBigIntWithExponent(t *testing.T) {
  482. type Inp struct {
  483. val *big.Int
  484. exp int32
  485. }
  486. tests := map[Inp]string{
  487. Inp{big.NewInt(123412345), -3}: "123412.345",
  488. Inp{big.NewInt(2234), -1}: "223.4",
  489. Inp{big.NewInt(323412345), 1}: "3234123450",
  490. Inp{big.NewInt(423412345), 0}: "423412345",
  491. Inp{big.NewInt(52341235), -5}: "523.41235",
  492. Inp{big.NewInt(623412345), -6}: "623.412345",
  493. Inp{big.NewInt(723412345), -7}: "72.3412345",
  494. }
  495. // add negatives
  496. for p, s := range tests {
  497. if p.val.Cmp(Zero.value) > 0 {
  498. tests[Inp{p.val.Neg(p.val), p.exp}] = "-" + s
  499. }
  500. }
  501. for input, s := range tests {
  502. d := NewFromBigInt(input.val, input.exp)
  503. if d.String() != s {
  504. t.Errorf("expected %s, got %s (%s, %d)",
  505. s, d.String(),
  506. d.value.String(), d.exp)
  507. }
  508. }
  509. }
  510. func TestJSON(t *testing.T) {
  511. for _, x := range testTable {
  512. s := x.short
  513. var doc struct {
  514. Amount Decimal `json:"amount"`
  515. }
  516. docStr := `{"amount":"` + s + `"}`
  517. docStrNumber := `{"amount":` + s + `}`
  518. err := json.Unmarshal([]byte(docStr), &doc)
  519. if err != nil {
  520. t.Errorf("error unmarshaling %s: %v", docStr, err)
  521. } else if doc.Amount.String() != s {
  522. t.Errorf("expected %s, got %s (%s, %d)",
  523. s, doc.Amount.String(),
  524. doc.Amount.value.String(), doc.Amount.exp)
  525. }
  526. out, err := json.Marshal(&doc)
  527. if err != nil {
  528. t.Errorf("error marshaling %+v: %v", doc, err)
  529. } else if string(out) != docStr {
  530. t.Errorf("expected %s, got %s", docStr, string(out))
  531. }
  532. // make sure unquoted marshalling works too
  533. MarshalJSONWithoutQuotes = true
  534. out, err = json.Marshal(&doc)
  535. if err != nil {
  536. t.Errorf("error marshaling %+v: %v", doc, err)
  537. } else if string(out) != docStrNumber {
  538. t.Errorf("expected %s, got %s", docStrNumber, string(out))
  539. }
  540. MarshalJSONWithoutQuotes = false
  541. }
  542. }
  543. func TestUnmarshalJSONNull(t *testing.T) {
  544. var doc struct {
  545. Amount Decimal `json:"amount"`
  546. }
  547. docStr := `{"amount": null}`
  548. err := json.Unmarshal([]byte(docStr), &doc)
  549. if err != nil {
  550. t.Errorf("error unmarshaling %s: %v", docStr, err)
  551. } else if !doc.Amount.Equal(Zero) {
  552. t.Errorf("expected Zero, got %s (%s, %d)",
  553. doc.Amount.String(),
  554. doc.Amount.value.String(), doc.Amount.exp)
  555. }
  556. }
  557. func TestBadJSON(t *testing.T) {
  558. for _, testCase := range []string{
  559. "]o_o[",
  560. "{",
  561. `{"amount":""`,
  562. `{"amount":""}`,
  563. `{"amount":"nope"}`,
  564. `0.333`,
  565. } {
  566. var doc struct {
  567. Amount Decimal `json:"amount"`
  568. }
  569. err := json.Unmarshal([]byte(testCase), &doc)
  570. if err == nil {
  571. t.Errorf("expected error, got %+v", doc)
  572. }
  573. }
  574. }
  575. func TestNullDecimalJSON(t *testing.T) {
  576. for _, x := range testTable {
  577. s := x.short
  578. var doc struct {
  579. Amount NullDecimal `json:"amount"`
  580. }
  581. docStr := `{"amount":"` + s + `"}`
  582. docStrNumber := `{"amount":` + s + `}`
  583. err := json.Unmarshal([]byte(docStr), &doc)
  584. if err != nil {
  585. t.Errorf("error unmarshaling %s: %v", docStr, err)
  586. } else {
  587. if !doc.Amount.Valid {
  588. t.Errorf("expected %s to be valid (not NULL), got Valid = false", s)
  589. }
  590. if doc.Amount.Decimal.String() != s {
  591. t.Errorf("expected %s, got %s (%s, %d)",
  592. s, doc.Amount.Decimal.String(),
  593. doc.Amount.Decimal.value.String(), doc.Amount.Decimal.exp)
  594. }
  595. }
  596. out, err := json.Marshal(&doc)
  597. if err != nil {
  598. t.Errorf("error marshaling %+v: %v", doc, err)
  599. } else if string(out) != docStr {
  600. t.Errorf("expected %s, got %s", docStr, string(out))
  601. }
  602. // make sure unquoted marshalling works too
  603. MarshalJSONWithoutQuotes = true
  604. out, err = json.Marshal(&doc)
  605. if err != nil {
  606. t.Errorf("error marshaling %+v: %v", doc, err)
  607. } else if string(out) != docStrNumber {
  608. t.Errorf("expected %s, got %s", docStrNumber, string(out))
  609. }
  610. MarshalJSONWithoutQuotes = false
  611. }
  612. var doc struct {
  613. Amount NullDecimal `json:"amount"`
  614. }
  615. docStr := `{"amount": null}`
  616. err := json.Unmarshal([]byte(docStr), &doc)
  617. if err != nil {
  618. t.Errorf("error unmarshaling %s: %v", docStr, err)
  619. } else if doc.Amount.Valid {
  620. t.Errorf("expected null value to have Valid = false, got Valid = true and Decimal = %s (%s, %d)",
  621. doc.Amount.Decimal.String(),
  622. doc.Amount.Decimal.value.String(), doc.Amount.Decimal.exp)
  623. }
  624. expected := `{"amount":null}`
  625. out, err := json.Marshal(&doc)
  626. if err != nil {
  627. t.Errorf("error marshaling %+v: %v", doc, err)
  628. } else if string(out) != expected {
  629. t.Errorf("expected %s, got %s", expected, string(out))
  630. }
  631. // make sure unquoted marshalling works too
  632. MarshalJSONWithoutQuotes = true
  633. expectedUnquoted := `{"amount":null}`
  634. out, err = json.Marshal(&doc)
  635. if err != nil {
  636. t.Errorf("error marshaling %+v: %v", doc, err)
  637. } else if string(out) != expectedUnquoted {
  638. t.Errorf("expected %s, got %s", expectedUnquoted, string(out))
  639. }
  640. MarshalJSONWithoutQuotes = false
  641. }
  642. func TestNullDecimalBadJSON(t *testing.T) {
  643. for _, testCase := range []string{
  644. "]o_o[",
  645. "{",
  646. `{"amount":""`,
  647. `{"amount":""}`,
  648. `{"amount":"nope"}`,
  649. `{"amount":nope}`,
  650. `0.333`,
  651. } {
  652. var doc struct {
  653. Amount NullDecimal `json:"amount"`
  654. }
  655. err := json.Unmarshal([]byte(testCase), &doc)
  656. if err == nil {
  657. t.Errorf("expected error, got %+v", doc)
  658. }
  659. }
  660. }
  661. func TestXML(t *testing.T) {
  662. for _, x := range testTable {
  663. s := x.short
  664. var doc struct {
  665. XMLName xml.Name `xml:"account"`
  666. Amount Decimal `xml:"amount"`
  667. }
  668. docStr := `<account><amount>` + s + `</amount></account>`
  669. err := xml.Unmarshal([]byte(docStr), &doc)
  670. if err != nil {
  671. t.Errorf("error unmarshaling %s: %v", docStr, err)
  672. } else if doc.Amount.String() != s {
  673. t.Errorf("expected %s, got %s (%s, %d)",
  674. s, doc.Amount.String(),
  675. doc.Amount.value.String(), doc.Amount.exp)
  676. }
  677. out, err := xml.Marshal(&doc)
  678. if err != nil {
  679. t.Errorf("error marshaling %+v: %v", doc, err)
  680. } else if string(out) != docStr {
  681. t.Errorf("expected %s, got %s", docStr, string(out))
  682. }
  683. }
  684. }
  685. func TestBadXML(t *testing.T) {
  686. for _, testCase := range []string{
  687. "o_o",
  688. "<abc",
  689. "<account><amount>7",
  690. `<html><body></body></html>`,
  691. `<account><amount></amount></account>`,
  692. `<account><amount>nope</amount></account>`,
  693. `0.333`,
  694. } {
  695. var doc struct {
  696. XMLName xml.Name `xml:"account"`
  697. Amount Decimal `xml:"amount"`
  698. }
  699. err := xml.Unmarshal([]byte(testCase), &doc)
  700. if err == nil {
  701. t.Errorf("expected error, got %+v", doc)
  702. }
  703. }
  704. }
  705. func TestDecimal_rescale(t *testing.T) {
  706. type Inp struct {
  707. int int64
  708. exp int32
  709. rescale int32
  710. }
  711. tests := map[Inp]string{
  712. Inp{1234, -3, -5}: "1.234",
  713. Inp{1234, -3, 0}: "1",
  714. Inp{1234, 3, 0}: "1234000",
  715. Inp{1234, -4, -4}: "0.1234",
  716. }
  717. // add negatives
  718. for p, s := range tests {
  719. if p.int > 0 {
  720. tests[Inp{-p.int, p.exp, p.rescale}] = "-" + s
  721. }
  722. }
  723. for input, s := range tests {
  724. d := New(input.int, input.exp).rescale(input.rescale)
  725. if d.String() != s {
  726. t.Errorf("expected %s, got %s (%s, %d)",
  727. s, d.String(),
  728. d.value.String(), d.exp)
  729. }
  730. // test StringScaled
  731. s2 := New(input.int, input.exp).StringScaled(input.rescale)
  732. if s2 != s {
  733. t.Errorf("expected %s, got %s", s, s2)
  734. }
  735. }
  736. }
  737. func TestDecimal_Floor(t *testing.T) {
  738. assertFloor := func(input, expected Decimal) {
  739. got := input.Floor()
  740. if !got.Equal(expected) {
  741. t.Errorf("Floor(%s): got %s, expected %s", input, got, expected)
  742. }
  743. }
  744. type testDataString struct {
  745. input string
  746. expected string
  747. }
  748. testsWithStrings := []testDataString{
  749. {"1.999", "1"},
  750. {"1", "1"},
  751. {"1.01", "1"},
  752. {"0", "0"},
  753. {"0.9", "0"},
  754. {"0.1", "0"},
  755. {"-0.9", "-1"},
  756. {"-0.1", "-1"},
  757. {"-1.00", "-1"},
  758. {"-1.01", "-2"},
  759. {"-1.999", "-2"},
  760. }
  761. for _, test := range testsWithStrings {
  762. expected, _ := NewFromString(test.expected)
  763. input, _ := NewFromString(test.input)
  764. assertFloor(input, expected)
  765. }
  766. type testDataDecimal struct {
  767. input Decimal
  768. expected string
  769. }
  770. testsWithDecimals := []testDataDecimal{
  771. {New(100, -1), "10"},
  772. {New(10, 0), "10"},
  773. {New(1, 1), "10"},
  774. {New(1999, -3), "1"},
  775. {New(101, -2), "1"},
  776. {New(1, 0), "1"},
  777. {New(0, 0), "0"},
  778. {New(9, -1), "0"},
  779. {New(1, -1), "0"},
  780. {New(-1, -1), "-1"},
  781. {New(-9, -1), "-1"},
  782. {New(-1, 0), "-1"},
  783. {New(-101, -2), "-2"},
  784. {New(-1999, -3), "-2"},
  785. }
  786. for _, test := range testsWithDecimals {
  787. expected, _ := NewFromString(test.expected)
  788. assertFloor(test.input, expected)
  789. }
  790. }
  791. func TestDecimal_Ceil(t *testing.T) {
  792. assertCeil := func(input, expected Decimal) {
  793. got := input.Ceil()
  794. if !got.Equal(expected) {
  795. t.Errorf("Ceil(%s): got %s, expected %s", input, got, expected)
  796. }
  797. }
  798. type testDataString struct {
  799. input string
  800. expected string
  801. }
  802. testsWithStrings := []testDataString{
  803. {"1.999", "2"},
  804. {"1", "1"},
  805. {"1.01", "2"},
  806. {"0", "0"},
  807. {"0.9", "1"},
  808. {"0.1", "1"},
  809. {"-0.9", "0"},
  810. {"-0.1", "0"},
  811. {"-1.00", "-1"},
  812. {"-1.01", "-1"},
  813. {"-1.999", "-1"},
  814. }
  815. for _, test := range testsWithStrings {
  816. expected, _ := NewFromString(test.expected)
  817. input, _ := NewFromString(test.input)
  818. assertCeil(input, expected)
  819. }
  820. type testDataDecimal struct {
  821. input Decimal
  822. expected string
  823. }
  824. testsWithDecimals := []testDataDecimal{
  825. {New(100, -1), "10"},
  826. {New(10, 0), "10"},
  827. {New(1, 1), "10"},
  828. {New(1999, -3), "2"},
  829. {New(101, -2), "2"},
  830. {New(1, 0), "1"},
  831. {New(0, 0), "0"},
  832. {New(9, -1), "1"},
  833. {New(1, -1), "1"},
  834. {New(-1, -1), "0"},
  835. {New(-9, -1), "0"},
  836. {New(-1, 0), "-1"},
  837. {New(-101, -2), "-1"},
  838. {New(-1999, -3), "-1"},
  839. }
  840. for _, test := range testsWithDecimals {
  841. expected, _ := NewFromString(test.expected)
  842. assertCeil(test.input, expected)
  843. }
  844. }
  845. func TestDecimal_RoundAndStringFixed(t *testing.T) {
  846. type testData struct {
  847. input string
  848. places int32
  849. expected string
  850. expectedFixed string
  851. }
  852. tests := []testData{
  853. {"1.454", 0, "1", ""},
  854. {"1.454", 1, "1.5", ""},
  855. {"1.454", 2, "1.45", ""},
  856. {"1.454", 3, "1.454", ""},
  857. {"1.454", 4, "1.454", "1.4540"},
  858. {"1.454", 5, "1.454", "1.45400"},
  859. {"1.554", 0, "2", ""},
  860. {"1.554", 1, "1.6", ""},
  861. {"1.554", 2, "1.55", ""},
  862. {"0.554", 0, "1", ""},
  863. {"0.454", 0, "0", ""},
  864. {"0.454", 5, "0.454", "0.45400"},
  865. {"0", 0, "0", ""},
  866. {"0", 1, "0", "0.0"},
  867. {"0", 2, "0", "0.00"},
  868. {"0", -1, "0", ""},
  869. {"5", 2, "5", "5.00"},
  870. {"5", 1, "5", "5.0"},
  871. {"5", 0, "5", ""},
  872. {"500", 2, "500", "500.00"},
  873. {"545", -1, "550", ""},
  874. {"545", -2, "500", ""},
  875. {"545", -3, "1000", ""},
  876. {"545", -4, "0", ""},
  877. {"499", -3, "0", ""},
  878. {"499", -4, "0", ""},
  879. }
  880. // add negative number tests
  881. for _, test := range tests {
  882. expected := test.expected
  883. if expected != "0" {
  884. expected = "-" + expected
  885. }
  886. expectedStr := test.expectedFixed
  887. if strings.ContainsAny(expectedStr, "123456789") && expectedStr != "" {
  888. expectedStr = "-" + expectedStr
  889. }
  890. tests = append(tests,
  891. testData{"-" + test.input, test.places, expected, expectedStr})
  892. }
  893. for _, test := range tests {
  894. d, err := NewFromString(test.input)
  895. if err != nil {
  896. t.Fatal(err)
  897. }
  898. // test Round
  899. expected, err := NewFromString(test.expected)
  900. if err != nil {
  901. t.Fatal(err)
  902. }
  903. got := d.Round(test.places)
  904. if !got.Equal(expected) {
  905. t.Errorf("Rounding %s to %d places, got %s, expected %s",
  906. d, test.places, got, expected)
  907. }
  908. // test StringFixed
  909. if test.expectedFixed == "" {
  910. test.expectedFixed = test.expected
  911. }
  912. gotStr := d.StringFixed(test.places)
  913. if gotStr != test.expectedFixed {
  914. t.Errorf("(%s).StringFixed(%d): got %s, expected %s",
  915. d, test.places, gotStr, test.expectedFixed)
  916. }
  917. }
  918. }
  919. func TestDecimal_RoundUpAndStringFixed(t *testing.T) {
  920. type testData struct {
  921. input string
  922. places int32
  923. expected string
  924. expectedFixed string
  925. }
  926. tests := []testData{
  927. {"1.454", 0, "2", ""},
  928. {"1.454", 1, "1.5", ""},
  929. {"1.454", 2, "1.46", ""},
  930. {"1.454", 3, "1.454", ""},
  931. {"1.454", 4, "1.454", "1.4540"},
  932. {"1.454", 5, "1.454", "1.45400"},
  933. {"1.554", 0, "2", ""},
  934. {"1.554", 1, "1.6", ""},
  935. {"1.554", 2, "1.56", ""},
  936. {"0.554", 0, "1", ""},
  937. {"0.454", 0, "1", ""},
  938. {"0.454", 5, "0.454", "0.45400"},
  939. {"0", 0, "0", ""},
  940. {"0", 1, "0", "0.0"},
  941. {"0", 2, "0", "0.00"},
  942. {"0", -1, "0", ""},
  943. {"5", 2, "5", "5.00"},
  944. {"5", 1, "5", "5.0"},
  945. {"5", 0, "5", ""},
  946. {"500", 2, "500", "500.00"},
  947. {"545", -1, "550", ""},
  948. {"545", -2, "600", ""},
  949. {"545", -3, "1000", ""},
  950. {"545", -4, "10000", ""},
  951. {"499", -3, "1000", ""},
  952. {"499", -4, "10000", ""},
  953. {"1.1001", 2, "1.11", ""},
  954. {"-1.1001", 2, "-1.10", ""},
  955. {"-1.454", 0, "-1", ""},
  956. {"-1.454", 1, "-1.4", ""},
  957. {"-1.454", 2, "-1.45", ""},
  958. {"-1.454", 3, "-1.454", ""},
  959. {"-1.454", 4, "-1.454", "-1.4540"},
  960. {"-1.454", 5, "-1.454", "-1.45400"},
  961. {"-1.554", 0, "-1", ""},
  962. {"-1.554", 1, "-1.5", ""},
  963. {"-1.554", 2, "-1.55", ""},
  964. {"-0.554", 0, "0", ""},
  965. {"-0.454", 0, "0", ""},
  966. {"-0.454", 5, "-0.454", "-0.45400"},
  967. {"-5", 2, "-5", "-5.00"},
  968. {"-5", 1, "-5", "-5.0"},
  969. {"-5", 0, "-5", ""},
  970. {"-500", 2, "-500", "-500.00"},
  971. {"-545", -1, "-540", ""},
  972. {"-545", -2, "-500", ""},
  973. {"-545", -3, "0", ""},
  974. {"-545", -4, "0", ""},
  975. {"-499", -3, "0", ""},
  976. {"-499", -4, "0", ""},
  977. }
  978. for _, test := range tests {
  979. d, err := NewFromString(test.input)
  980. if err != nil {
  981. t.Fatal(err)
  982. }
  983. // test Round
  984. expected, err := NewFromString(test.expected)
  985. if err != nil {
  986. t.Fatal(err)
  987. }
  988. got := d.RoundUp(test.places)
  989. if !got.Equal(expected) {
  990. t.Errorf("Rounding up %s to %d places, got %s, expected %s",
  991. d, test.places, got, expected)
  992. }
  993. // test StringFixed
  994. if test.expectedFixed == "" {
  995. test.expectedFixed = test.expected
  996. }
  997. gotStr := got.StringFixed(test.places)
  998. if gotStr != test.expectedFixed {
  999. t.Errorf("(%s).StringFixed(%d): got %s, expected %s",
  1000. d, test.places, gotStr, test.expectedFixed)
  1001. }
  1002. }
  1003. }
  1004. func TestDecimal_RoundDownAndStringFixed(t *testing.T) {
  1005. type testData struct {
  1006. input string
  1007. places int32
  1008. expected string
  1009. expectedFixed string
  1010. }
  1011. tests := []testData{
  1012. {"1.454", 0, "1", ""},
  1013. {"1.454", 1, "1.4", ""},
  1014. {"1.454", 2, "1.45", ""},
  1015. {"1.454", 3, "1.454", ""},
  1016. {"1.454", 4, "1.454", "1.4540"},
  1017. {"1.454", 5, "1.454", "1.45400"},
  1018. {"1.554", 0, "1", ""},
  1019. {"1.554", 1, "1.5", ""},
  1020. {"1.554", 2, "1.55", ""},
  1021. {"0.554", 0, "0", ""},
  1022. {"0.454", 0, "0", ""},
  1023. {"0.454", 5, "0.454", "0.45400"},
  1024. {"0", 0, "0", ""},
  1025. {"0", 1, "0", "0.0"},
  1026. {"0", 2, "0", "0.00"},
  1027. {"0", -1, "0", ""},
  1028. {"5", 2, "5", "5.00"},
  1029. {"5", 1, "5", "5.0"},
  1030. {"5", 0, "5", ""},
  1031. {"500", 2, "500", "500.00"},
  1032. {"545", -1, "540", ""},
  1033. {"545", -2, "500", ""},
  1034. {"545", -3, "0", ""},
  1035. {"545", -4, "0", ""},
  1036. {"499", -3, "0", ""},
  1037. {"499", -4, "0", ""},
  1038. {"1.1001", 2, "1.10", ""},
  1039. {"-1.1001", 2, "-1.11", ""},
  1040. {"-1.454", 0, "-2", ""},
  1041. {"-1.454", 1, "-1.5", ""},
  1042. {"-1.454", 2, "-1.46", ""},
  1043. {"-1.454", 3, "-1.454", ""},
  1044. {"-1.454", 4, "-1.454", "-1.4540"},
  1045. {"-1.454", 5, "-1.454", "-1.45400"},
  1046. {"-1.554", 0, "-2", ""},
  1047. {"-1.554", 1, "-1.6", ""},
  1048. {"-1.554", 2, "-1.56", ""},
  1049. {"-0.554", 0, "-1", ""},
  1050. {"-0.454", 0, "-1", ""},
  1051. {"-0.454", 5, "-0.454", "-0.45400"},
  1052. {"-5", 2, "-5", "-5.00"},
  1053. {"-5", 1, "-5", "-5.0"},
  1054. {"-5", 0, "-5", ""},
  1055. {"-500", 2, "-500", "-500.00"},
  1056. {"-545", -1, "-550", ""},
  1057. {"-545", -2, "-600", ""},
  1058. {"-545", -3, "-1000", ""},
  1059. {"-545", -4, "-10000", ""},
  1060. {"-499", -3, "-1000", ""},
  1061. {"-499", -4, "-10000", ""},
  1062. }
  1063. for _, test := range tests {
  1064. d, err := NewFromString(test.input)
  1065. if err != nil {
  1066. t.Fatal(err)
  1067. }
  1068. // test Round
  1069. expected, err := NewFromString(test.expected)
  1070. if err != nil {
  1071. t.Fatal(err)
  1072. }
  1073. got := d.RoundDown(test.places)
  1074. if !got.Equal(expected) {
  1075. t.Errorf("Rounding down %s to %d places, got %s, expected %s",
  1076. d, test.places, got, expected)
  1077. }
  1078. // test StringFixed
  1079. if test.expectedFixed == "" {
  1080. test.expectedFixed = test.expected
  1081. }
  1082. gotStr := got.StringFixed(test.places)
  1083. if gotStr != test.expectedFixed {
  1084. t.Errorf("(%s).StringFixed(%d): got %s, expected %s",
  1085. d, test.places, gotStr, test.expectedFixed)
  1086. }
  1087. }
  1088. }
  1089. func TestDecimal_BankRoundAndStringFixed(t *testing.T) {
  1090. type testData struct {
  1091. input string
  1092. places int32
  1093. expected string
  1094. expectedFixed string
  1095. }
  1096. tests := []testData{
  1097. {"1.454", 0, "1", ""},
  1098. {"1.454", 1, "1.5", ""},
  1099. {"1.454", 2, "1.45", ""},
  1100. {"1.454", 3, "1.454", ""},
  1101. {"1.454", 4, "1.454", "1.4540"},
  1102. {"1.454", 5, "1.454", "1.45400"},
  1103. {"1.554", 0, "2", ""},
  1104. {"1.554", 1, "1.6", ""},
  1105. {"1.554", 2, "1.55", ""},
  1106. {"0.554", 0, "1", ""},
  1107. {"0.454", 0, "0", ""},
  1108. {"0.454", 5, "0.454", "0.45400"},
  1109. {"0", 0, "0", ""},
  1110. {"0", 1, "0", "0.0"},
  1111. {"0", 2, "0", "0.00"},
  1112. {"0", -1, "0", ""},
  1113. {"5", 2, "5", "5.00"},
  1114. {"5", 1, "5", "5.0"},
  1115. {"5", 0, "5", ""},
  1116. {"500", 2, "500", "500.00"},
  1117. {"545", -2, "500", ""},
  1118. {"545", -3, "1000", ""},
  1119. {"545", -4, "0", ""},
  1120. {"499", -3, "0", ""},
  1121. {"499", -4, "0", ""},
  1122. {"1.45", 1, "1.4", ""},
  1123. {"1.55", 1, "1.6", ""},
  1124. {"1.65", 1, "1.6", ""},
  1125. {"545", -1, "540", ""},
  1126. {"565", -1, "560", ""},
  1127. {"555", -1, "560", ""},
  1128. }
  1129. // add negative number tests
  1130. for _, test := range tests {
  1131. expected := test.expected
  1132. if expected != "0" {
  1133. expected = "-" + expected
  1134. }
  1135. expectedStr := test.expectedFixed
  1136. if strings.ContainsAny(expectedStr, "123456789") && expectedStr != "" {
  1137. expectedStr = "-" + expectedStr
  1138. }
  1139. tests = append(tests,
  1140. testData{"-" + test.input, test.places, expected, expectedStr})
  1141. }
  1142. for _, test := range tests {
  1143. d, err := NewFromString(test.input)
  1144. if err != nil {
  1145. panic(err)
  1146. }
  1147. // test Round
  1148. expected, err := NewFromString(test.expected)
  1149. if err != nil {
  1150. panic(err)
  1151. }
  1152. got := d.RoundBank(test.places)
  1153. if !got.Equal(expected) {
  1154. t.Errorf("Bank Rounding %s to %d places, got %s, expected %s",
  1155. d, test.places, got, expected)
  1156. }
  1157. // test StringFixed
  1158. if test.expectedFixed == "" {
  1159. test.expectedFixed = test.expected
  1160. }
  1161. gotStr := d.StringFixedBank(test.places)
  1162. if gotStr != test.expectedFixed {
  1163. t.Errorf("(%s).StringFixed(%d): got %s, expected %s",
  1164. d, test.places, gotStr, test.expectedFixed)
  1165. }
  1166. }
  1167. }
  1168. func TestDecimal_Uninitialized(t *testing.T) {
  1169. a := Decimal{}
  1170. b := Decimal{}
  1171. decs := []Decimal{
  1172. a,
  1173. a.rescale(10),
  1174. a.Abs(),
  1175. a.Add(b),
  1176. a.Sub(b),
  1177. a.Mul(b),
  1178. a.Shift(0),
  1179. a.Div(New(1, -1)),
  1180. a.Round(2),
  1181. a.Floor(),
  1182. a.Ceil(),
  1183. a.Truncate(2),
  1184. }
  1185. for _, d := range decs {
  1186. if d.String() != "0" {
  1187. t.Errorf("expected 0, got %s", d.String())
  1188. }
  1189. if d.StringFixed(3) != "0.000" {
  1190. t.Errorf("expected 0, got %s", d.StringFixed(3))
  1191. }
  1192. if d.StringScaled(-2) != "0" {
  1193. t.Errorf("expected 0, got %s", d.StringScaled(-2))
  1194. }
  1195. }
  1196. if a.Cmp(b) != 0 {
  1197. t.Errorf("a != b")
  1198. }
  1199. if a.Sign() != 0 {
  1200. t.Errorf("a.Sign() != 0")
  1201. }
  1202. if a.Exponent() != 0 {
  1203. t.Errorf("a.Exponent() != 0")
  1204. }
  1205. if a.IntPart() != 0 {
  1206. t.Errorf("a.IntPar() != 0")
  1207. }
  1208. f, _ := a.Float64()
  1209. if f != 0 {
  1210. t.Errorf("a.Float64() != 0")
  1211. }
  1212. if a.Rat().RatString() != "0" {
  1213. t.Errorf("a.Rat() != 0, got %s", a.Rat().RatString())
  1214. }
  1215. }
  1216. func TestDecimal_Add(t *testing.T) {
  1217. type Inp struct {
  1218. a string
  1219. b string
  1220. }
  1221. inputs := map[Inp]string{
  1222. Inp{"2", "3"}: "5",
  1223. Inp{"2454495034", "3451204593"}: "5905699627",
  1224. Inp{"24544.95034", ".3451204593"}: "24545.2954604593",
  1225. Inp{".1", ".1"}: "0.2",
  1226. Inp{".1", "-.1"}: "0",
  1227. Inp{"0", "1.001"}: "1.001",
  1228. }
  1229. for inp, res := range inputs {
  1230. a, err := NewFromString(inp.a)
  1231. if err != nil {
  1232. t.FailNow()
  1233. }
  1234. b, err := NewFromString(inp.b)
  1235. if err != nil {
  1236. t.FailNow()
  1237. }
  1238. c := a.Add(b)
  1239. if c.String() != res {
  1240. t.Errorf("expected %s, got %s", res, c.String())
  1241. }
  1242. }
  1243. }
  1244. func TestDecimal_Sub(t *testing.T) {
  1245. type Inp struct {
  1246. a string
  1247. b string
  1248. }
  1249. inputs := map[Inp]string{
  1250. Inp{"2", "3"}: "-1",
  1251. Inp{"12", "3"}: "9",
  1252. Inp{"-2", "9"}: "-11",
  1253. Inp{"2454495034", "3451204593"}: "-996709559",
  1254. Inp{"24544.95034", ".3451204593"}: "24544.6052195407",
  1255. Inp{".1", "-.1"}: "0.2",
  1256. Inp{".1", ".1"}: "0",
  1257. Inp{"0", "1.001"}: "-1.001",
  1258. Inp{"1.001", "0"}: "1.001",
  1259. Inp{"2.3", ".3"}: "2",
  1260. }
  1261. for inp, res := range inputs {
  1262. a, err := NewFromString(inp.a)
  1263. if err != nil {
  1264. t.FailNow()
  1265. }
  1266. b, err := NewFromString(inp.b)
  1267. if err != nil {
  1268. t.FailNow()
  1269. }
  1270. c := a.Sub(b)
  1271. if c.String() != res {
  1272. t.Errorf("expected %s, got %s", res, c.String())
  1273. }
  1274. }
  1275. }
  1276. func TestDecimal_Neg(t *testing.T) {
  1277. inputs := map[string]string{
  1278. "0": "0",
  1279. "10": "-10",
  1280. "5.56": "-5.56",
  1281. "-10": "10",
  1282. "-5.56": "5.56",
  1283. }
  1284. for inp, res := range inputs {
  1285. a, err := NewFromString(inp)
  1286. if err != nil {
  1287. t.FailNow()
  1288. }
  1289. b := a.Neg()
  1290. if b.String() != res {
  1291. t.Errorf("expected %s, got %s", res, b.String())
  1292. }
  1293. }
  1294. }
  1295. func TestDecimal_NegFromEmpty(t *testing.T) {
  1296. a := Decimal{}
  1297. b := a.Neg()
  1298. if b.String() != "0" {
  1299. t.Errorf("expected %s, got %s", "0", b)
  1300. }
  1301. }
  1302. func TestDecimal_Mul(t *testing.T) {
  1303. type Inp struct {
  1304. a string
  1305. b string
  1306. }
  1307. inputs := map[Inp]string{
  1308. Inp{"2", "3"}: "6",
  1309. Inp{"2454495034", "3451204593"}: "8470964534836491162",
  1310. Inp{"24544.95034", ".3451204593"}: "8470.964534836491162",
  1311. Inp{".1", ".1"}: "0.01",
  1312. Inp{"0", "1.001"}: "0",
  1313. }
  1314. for inp, res := range inputs {
  1315. a, err := NewFromString(inp.a)
  1316. if err != nil {
  1317. t.FailNow()
  1318. }
  1319. b, err := NewFromString(inp.b)
  1320. if err != nil {
  1321. t.FailNow()
  1322. }
  1323. c := a.Mul(b)
  1324. if c.String() != res {
  1325. t.Errorf("expected %s, got %s", res, c.String())
  1326. }
  1327. }
  1328. // positive scale
  1329. c := New(1234, 5).Mul(New(45, -1))
  1330. if c.String() != "555300000" {
  1331. t.Errorf("Expected %s, got %s", "555300000", c.String())
  1332. }
  1333. }
  1334. func TestDecimal_Shift(t *testing.T) {
  1335. type Inp struct {
  1336. a string
  1337. b int32
  1338. }
  1339. inputs := map[Inp]string{
  1340. Inp{"6", 3}: "6000",
  1341. Inp{"10", -2}: "0.1",
  1342. Inp{"2.2", 1}: "22",
  1343. Inp{"-2.2", -1}: "-0.22",
  1344. Inp{"12.88", 5}: "1288000",
  1345. Inp{"-10234274355545544493", -3}: "-10234274355545544.493",
  1346. Inp{"-4612301402398.4753343454", 5}: "-461230140239847533.43454",
  1347. }
  1348. for inp, expectedStr := range inputs {
  1349. num, _ := NewFromString(inp.a)
  1350. got := num.Shift(inp.b)
  1351. expected, _ := NewFromString(expectedStr)
  1352. if !got.Equal(expected) {
  1353. t.Errorf("expected %v when shifting %v by %v, got %v",
  1354. expected, num, inp.b, got)
  1355. }
  1356. }
  1357. }
  1358. func TestDecimal_Div(t *testing.T) {
  1359. type Inp struct {
  1360. a string
  1361. b string
  1362. }
  1363. inputs := map[Inp]string{
  1364. Inp{"6", "3"}: "2",
  1365. Inp{"10", "2"}: "5",
  1366. Inp{"2.2", "1.1"}: "2",
  1367. Inp{"-2.2", "-1.1"}: "2",
  1368. Inp{"12.88", "5.6"}: "2.3",
  1369. Inp{"1023427554493", "43432632"}: "23563.5628642767953828", // rounded
  1370. Inp{"1", "434324545566634"}: "0.0000000000000023",
  1371. Inp{"1", "3"}: "0.3333333333333333",
  1372. Inp{"2", "3"}: "0.6666666666666667", // rounded
  1373. Inp{"10000", "3"}: "3333.3333333333333333",
  1374. Inp{"10234274355545544493", "-3"}: "-3411424785181848164.3333333333333333",
  1375. Inp{"-4612301402398.4753343454", "23.5"}: "-196268144782.9138440146978723",
  1376. }
  1377. for inp, expectedStr := range inputs {
  1378. num, err := NewFromString(inp.a)
  1379. if err != nil {
  1380. t.FailNow()
  1381. }
  1382. denom, err := NewFromString(inp.b)
  1383. if err != nil {
  1384. t.FailNow()
  1385. }
  1386. got := num.Div(denom)
  1387. expected, _ := NewFromString(expectedStr)
  1388. if !got.Equal(expected) {
  1389. t.Errorf("expected %v when dividing %v by %v, got %v",
  1390. expected, num, denom, got)
  1391. }
  1392. got2 := num.DivRound(denom, int32(DivisionPrecision))
  1393. if !got2.Equal(expected) {
  1394. t.Errorf("expected %v on DivRound (%v,%v), got %v", expected, num, denom, got2)
  1395. }
  1396. }
  1397. type Inp2 struct {
  1398. n int64
  1399. exp int32
  1400. n2 int64
  1401. exp2 int32
  1402. }
  1403. // test code path where exp > 0
  1404. inputs2 := map[Inp2]string{
  1405. Inp2{124, 10, 3, 1}: "41333333333.3333333333333333",
  1406. Inp2{124, 10, 3, 0}: "413333333333.3333333333333333",
  1407. Inp2{124, 10, 6, 1}: "20666666666.6666666666666667",
  1408. Inp2{124, 10, 6, 0}: "206666666666.6666666666666667",
  1409. Inp2{10, 10, 10, 1}: "1000000000",
  1410. }
  1411. for inp, expectedAbs := range inputs2 {
  1412. for i := -1; i <= 1; i += 2 {
  1413. for j := -1; j <= 1; j += 2 {
  1414. n := inp.n * int64(i)
  1415. n2 := inp.n2 * int64(j)
  1416. num := New(n, inp.exp)
  1417. denom := New(n2, inp.exp2)
  1418. expected := expectedAbs
  1419. if i != j {
  1420. expected = "-" + expectedAbs
  1421. }
  1422. got := num.Div(denom)
  1423. if got.String() != expected {
  1424. t.Errorf("expected %s when dividing %v by %v, got %v",
  1425. expected, num, denom, got)
  1426. }
  1427. }
  1428. }
  1429. }
  1430. }
  1431. func TestDecimal_QuoRem(t *testing.T) {
  1432. type Inp4 struct {
  1433. d string
  1434. d2 string
  1435. exp int32
  1436. q string
  1437. r string
  1438. }
  1439. cases := []Inp4{
  1440. {"10", "1", 0, "10", "0"},
  1441. {"1", "10", 0, "0", "1"},
  1442. {"1", "4", 2, "0.25", "0"},
  1443. {"1", "8", 2, "0.12", "0.04"},
  1444. {"10", "3", 1, "3.3", "0.1"},
  1445. {"100", "3", 1, "33.3", "0.1"},
  1446. {"1000", "10", -3, "0", "1000"},
  1447. {"1e-3", "2e-5", 0, "50", "0"},
  1448. {"1e-3", "2e-3", 1, "0.5", "0"},
  1449. {"4e-3", "0.8", 4, "5e-3", "0"},
  1450. {"4.1e-3", "0.8", 3, "5e-3", "1e-4"},
  1451. {"-4", "-3", 0, "1", "-1"},
  1452. {"-4", "3", 0, "-1", "-1"},
  1453. }
  1454. for _, inp4 := range cases {
  1455. d, _ := NewFromString(inp4.d)
  1456. d2, _ := NewFromString(inp4.d2)
  1457. prec := inp4.exp
  1458. q, r := d.QuoRem(d2, prec)
  1459. expectedQ, _ := NewFromString(inp4.q)
  1460. expectedR, _ := NewFromString(inp4.r)
  1461. if !q.Equal(expectedQ) || !r.Equal(expectedR) {
  1462. t.Errorf("bad QuoRem division %s , %s , %d got %v, %v expected %s , %s",
  1463. inp4.d, inp4.d2, prec, q, r, inp4.q, inp4.r)
  1464. }
  1465. if !d.Equal(d2.Mul(q).Add(r)) {
  1466. t.Errorf("not fitting: d=%v, d2= %v, prec=%d, q=%v, r=%v",
  1467. d, d2, prec, q, r)
  1468. }
  1469. if !q.Equal(q.Truncate(prec)) {
  1470. t.Errorf("quotient wrong precision: d=%v, d2= %v, prec=%d, q=%v, r=%v",
  1471. d, d2, prec, q, r)
  1472. }
  1473. if r.Abs().Cmp(d2.Abs().Mul(New(1, -prec))) >= 0 {
  1474. t.Errorf("remainder too large: d=%v, d2= %v, prec=%d, q=%v, r=%v",
  1475. d, d2, prec, q, r)
  1476. }
  1477. if r.value.Sign()*d.value.Sign() < 0 {
  1478. t.Errorf("signum of divisor and rest do not match: d=%v, d2= %v, prec=%d, q=%v, r=%v",
  1479. d, d2, prec, q, r)
  1480. }
  1481. }
  1482. }
  1483. type DivTestCase struct {
  1484. d Decimal
  1485. d2 Decimal
  1486. prec int32
  1487. }
  1488. func createDivTestCases() []DivTestCase {
  1489. res := make([]DivTestCase, 0)
  1490. var n int32 = 5
  1491. a := []int{1, 2, 3, 6, 7, 10, 100, 14, 5, 400, 0, 1000000, 1000000 + 1, 1000000 - 1}
  1492. for s := -1; s < 2; s = s + 2 { // 2
  1493. for s2 := -1; s2 < 2; s2 = s2 + 2 { // 2
  1494. for e1 := -n; e1 <= n; e1++ { // 2n+1
  1495. for e2 := -n; e2 <= n; e2++ { // 2n+1
  1496. var prec int32
  1497. for prec = -n; prec <= n; prec++ { // 2n+1
  1498. for _, v1 := range a { // 11
  1499. for _, v2 := range a { // 11, even if 0 is skipped
  1500. sign1 := New(int64(s), 0)
  1501. sign2 := New(int64(s2), 0)
  1502. d := sign1.Mul(New(int64(v1), e1))
  1503. d2 := sign2.Mul(New(int64(v2), e2))
  1504. res = append(res, DivTestCase{d, d2, prec})
  1505. }
  1506. }
  1507. }
  1508. }
  1509. }
  1510. }
  1511. }
  1512. return res
  1513. }
  1514. func TestDecimal_QuoRem2(t *testing.T) {
  1515. for _, tc := range createDivTestCases() {
  1516. d := tc.d
  1517. if sign(tc.d2) == 0 {
  1518. continue
  1519. }
  1520. d2 := tc.d2
  1521. prec := tc.prec
  1522. q, r := d.QuoRem(d2, prec)
  1523. // rule 1: d = d2*q +r
  1524. if !d.Equal(d2.Mul(q).Add(r)) {
  1525. t.Errorf("not fitting, d=%v, d2=%v, prec=%d, q=%v, r=%v",
  1526. d, d2, prec, q, r)
  1527. }
  1528. // rule 2: q is integral multiple of 10^(-prec)
  1529. if !q.Equal(q.Truncate(prec)) {
  1530. t.Errorf("quotient wrong precision, d=%v, d2=%v, prec=%d, q=%v, r=%v",
  1531. d, d2, prec, q, r)
  1532. }
  1533. // rule 3: abs(r)<abs(d) * 10^(-prec)
  1534. if r.Abs().Cmp(d2.Abs().Mul(New(1, -prec))) >= 0 {
  1535. t.Errorf("remainder too large, d=%v, d2=%v, prec=%d, q=%v, r=%v",
  1536. d, d2, prec, q, r)
  1537. }
  1538. // rule 4: r and d have the same sign
  1539. if r.value.Sign()*d.value.Sign() < 0 {
  1540. t.Errorf("signum of divisor and rest do not match, "+
  1541. "d=%v, d2=%v, prec=%d, q=%v, r=%v",
  1542. d, d2, prec, q, r)
  1543. }
  1544. }
  1545. }
  1546. // this is the old Div method from decimal
  1547. // Div returns d / d2. If it doesn't divide exactly, the result will have
  1548. // DivisionPrecision digits after the decimal point.
  1549. func (d Decimal) DivOld(d2 Decimal, prec int) Decimal {
  1550. // NOTE(vadim): division is hard, use Rat to do it
  1551. ratNum := d.Rat()
  1552. ratDenom := d2.Rat()
  1553. quoRat := big.NewRat(0, 1).Quo(ratNum, ratDenom)
  1554. // HACK(vadim): converting from Rat to Decimal inefficiently for now
  1555. ret, err := NewFromString(quoRat.FloatString(prec))
  1556. if err != nil {
  1557. panic(err) // this should never happen
  1558. }
  1559. return ret
  1560. }
  1561. func sign(d Decimal) int {
  1562. return d.value.Sign()
  1563. }
  1564. // rules for rounded divide, rounded to integer
  1565. // rounded_divide(d,d2) = q
  1566. // sign q * sign (d/d2) >= 0
  1567. // for d and d2 >0 :
  1568. // q is already rounded
  1569. // q = d/d2 + r , with r > -0.5 and r <= 0.5
  1570. // thus q-d/d2 = r, with r > -0.5 and r <= 0.5
  1571. // and d2 q -d = r d2 with r d2 > -d2/2 and r d2 <= d2/2
  1572. // and 2 (d2 q -d) = x with x > -d2 and x <= d2
  1573. // if we factor in precision then x > -d2 * 10^(-precision) and x <= d2 * 10(-precision)
  1574. func TestDecimal_DivRound(t *testing.T) {
  1575. cases := []struct {
  1576. d string
  1577. d2 string
  1578. prec int32
  1579. result string
  1580. }{
  1581. {"2", "2", 0, "1"},
  1582. {"1", "2", 0, "1"},
  1583. {"-1", "2", 0, "-1"},
  1584. {"-1", "-2", 0, "1"},
  1585. {"1", "-2", 0, "-1"},
  1586. {"1", "-20", 1, "-0.1"},
  1587. {"1", "-20", 2, "-0.05"},
  1588. {"1", "20.0000000000000000001", 1, "0"},
  1589. {"1", "19.9999999999999999999", 1, "0.1"},
  1590. }
  1591. for _, s := range cases {
  1592. d, _ := NewFromString(s.d)
  1593. d2, _ := NewFromString(s.d2)
  1594. result, _ := NewFromString(s.result)
  1595. prec := s.prec
  1596. q := d.DivRound(d2, prec)
  1597. if sign(q)*sign(d)*sign(d2) < 0 {
  1598. t.Errorf("sign of quotient wrong, got: %v/%v is about %v", d, d2, q)
  1599. }
  1600. x := q.Mul(d2).Abs().Sub(d.Abs()).Mul(New(2, 0))
  1601. if x.Cmp(d2.Abs().Mul(New(1, -prec))) > 0 {
  1602. t.Errorf("wrong rounding, got: %v/%v prec=%d is about %v", d, d2, prec, q)
  1603. }
  1604. if x.Cmp(d2.Abs().Mul(New(-1, -prec))) <= 0 {
  1605. t.Errorf("wrong rounding, got: %v/%v prec=%d is about %v", d, d2, prec, q)
  1606. }
  1607. if !q.Equal(result) {
  1608. t.Errorf("rounded division wrong %s / %s scale %d = %s, got %v", s.d, s.d2, prec, s.result, q)
  1609. }
  1610. }
  1611. }
  1612. func TestDecimal_DivRound2(t *testing.T) {
  1613. for _, tc := range createDivTestCases() {
  1614. d := tc.d
  1615. if sign(tc.d2) == 0 {
  1616. continue
  1617. }
  1618. d2 := tc.d2
  1619. prec := tc.prec
  1620. q := d.DivRound(d2, prec)
  1621. if sign(q)*sign(d)*sign(d2) < 0 {
  1622. t.Errorf("sign of quotient wrong, got: %v/%v is about %v", d, d2, q)
  1623. }
  1624. x := q.Mul(d2).Abs().Sub(d.Abs()).Mul(New(2, 0))
  1625. if x.Cmp(d2.Abs().Mul(New(1, -prec))) > 0 {
  1626. t.Errorf("wrong rounding, got: %v/%v prec=%d is about %v", d, d2, prec, q)
  1627. }
  1628. if x.Cmp(d2.Abs().Mul(New(-1, -prec))) <= 0 {
  1629. t.Errorf("wrong rounding, got: %v/%v prec=%d is about %v", d, d2, prec, q)
  1630. }
  1631. }
  1632. }
  1633. func TestDecimal_RoundCash(t *testing.T) {
  1634. tests := []struct {
  1635. d string
  1636. interval uint8
  1637. result string
  1638. }{
  1639. {"3.44", 5, "3.45"},
  1640. {"3.43", 5, "3.45"},
  1641. {"3.42", 5, "3.40"},
  1642. {"3.425", 5, "3.45"},
  1643. {"3.47", 5, "3.45"},
  1644. {"3.478", 5, "3.50"},
  1645. {"3.48", 5, "3.50"},
  1646. {"348", 5, "348"},
  1647. {"3.23", 10, "3.20"},
  1648. {"3.33", 10, "3.30"},
  1649. {"3.53", 10, "3.50"},
  1650. {"3.949", 10, "3.90"},
  1651. {"3.95", 10, "4.00"},
  1652. {"395", 10, "395"},
  1653. {"3.23", 25, "3.25"},
  1654. {"3.33", 25, "3.25"},
  1655. {"3.53", 25, "3.50"},
  1656. {"3.93", 25, "4.00"},
  1657. {"3.41", 25, "3.50"},
  1658. {"3.249", 50, "3.00"},
  1659. {"3.33", 50, "3.50"},
  1660. {"3.749999999", 50, "3.50"},
  1661. {"3.75", 50, "4.00"},
  1662. {"3.93", 50, "4.00"},
  1663. {"393", 50, "393"},
  1664. {"3.249", 100, "3.00"},
  1665. {"3.49999", 100, "3.00"},
  1666. {"3.50", 100, "4.00"},
  1667. {"3.75", 100, "4.00"},
  1668. {"3.93", 100, "4.00"},
  1669. {"393", 100, "393"},
  1670. }
  1671. for i, test := range tests {
  1672. d, _ := NewFromString(test.d)
  1673. haveRounded := d.RoundCash(test.interval)
  1674. result, _ := NewFromString(test.result)
  1675. if !haveRounded.Equal(result) {
  1676. t.Errorf("Index %d: Cash rounding for %q interval %d want %q, have %q", i, test.d, test.interval, test.result, haveRounded)
  1677. }
  1678. }
  1679. }
  1680. func TestDecimal_RoundCash_Panic(t *testing.T) {
  1681. defer func() {
  1682. if r := recover(); r != nil {
  1683. if have, ok := r.(string); ok {
  1684. const want = "Decimal does not support this Cash rounding interval `231`. Supported: 5, 10, 25, 50, 100"
  1685. if want != have {
  1686. t.Errorf("\nWant: %q\nHave: %q", want, have)
  1687. }
  1688. } else {
  1689. t.Errorf("Panic should contain an error string but got:\n%+v", r)
  1690. }
  1691. } else {
  1692. t.Error("Expecting a panic but got nothing")
  1693. }
  1694. }()
  1695. d, _ := NewFromString("1")
  1696. d.RoundCash(231)
  1697. }
  1698. func TestDecimal_Mod(t *testing.T) {
  1699. type Inp struct {
  1700. a string
  1701. b string
  1702. }
  1703. inputs := map[Inp]string{
  1704. Inp{"3", "2"}: "1",
  1705. Inp{"3451204593", "2454495034"}: "996709559",
  1706. Inp{"24544.95034", ".3451204593"}: "0.3283950433",
  1707. Inp{".1", ".1"}: "0",
  1708. Inp{"0", "1.001"}: "0",
  1709. Inp{"-7.5", "2"}: "-1.5",
  1710. Inp{"7.5", "-2"}: "1.5",
  1711. Inp{"-7.5", "-2"}: "-1.5",
  1712. }
  1713. for inp, res := range inputs {
  1714. a, err := NewFromString(inp.a)
  1715. if err != nil {
  1716. t.FailNow()
  1717. }
  1718. b, err := NewFromString(inp.b)
  1719. if err != nil {
  1720. t.FailNow()
  1721. }
  1722. c := a.Mod(b)
  1723. if c.String() != res {
  1724. t.Errorf("expected %s, got %s", res, c.String())
  1725. }
  1726. }
  1727. }
  1728. func TestDecimal_Overflow(t *testing.T) {
  1729. if !didPanic(func() { New(1, math.MinInt32).Mul(New(1, math.MinInt32)) }) {
  1730. t.Fatalf("should have gotten an overflow panic")
  1731. }
  1732. if !didPanic(func() { New(1, math.MaxInt32).Mul(New(1, math.MaxInt32)) }) {
  1733. t.Fatalf("should have gotten an overflow panic")
  1734. }
  1735. }
  1736. func TestDecimal_ExtremeValues(t *testing.T) {
  1737. // NOTE(vadim): this test takes pretty much forever
  1738. if testing.Short() {
  1739. t.Skip()
  1740. }
  1741. // NOTE(vadim): Seriously, the numbers involved are so large that this
  1742. // test will take way too long, so mark it as success if it takes over
  1743. // 1 second. The way this test typically fails (integer overflow) is that
  1744. // a wrong result appears quickly, so if it takes a long time then it is
  1745. // probably working properly.
  1746. // Why even bother testing this? Completeness, I guess. -Vadim
  1747. const timeLimit = 1 * time.Second
  1748. test := func(f func()) {
  1749. c := make(chan bool)
  1750. go func() {
  1751. f()
  1752. close(c)
  1753. }()
  1754. select {
  1755. case <-c:
  1756. case <-time.After(timeLimit):
  1757. }
  1758. }
  1759. test(func() {
  1760. got := New(123, math.MinInt32).Floor()
  1761. if !got.Equal(NewFromFloat(0)) {
  1762. t.Errorf("Error: got %s, expected 0", got)
  1763. }
  1764. })
  1765. test(func() {
  1766. got := New(123, math.MinInt32).Ceil()
  1767. if !got.Equal(NewFromFloat(1)) {
  1768. t.Errorf("Error: got %s, expected 1", got)
  1769. }
  1770. })
  1771. test(func() {
  1772. got := New(123, math.MinInt32).Rat().FloatString(10)
  1773. expected := "0.0000000000"
  1774. if got != expected {
  1775. t.Errorf("Error: got %s, expected %s", got, expected)
  1776. }
  1777. })
  1778. }
  1779. func TestIntPart(t *testing.T) {
  1780. for _, testCase := range []struct {
  1781. Dec string
  1782. IntPart int64
  1783. }{
  1784. {"0.01", 0},
  1785. {"12.1", 12},
  1786. {"9999.999", 9999},
  1787. {"-32768.01234", -32768},
  1788. } {
  1789. d, err := NewFromString(testCase.Dec)
  1790. if err != nil {
  1791. t.Fatal(err)
  1792. }
  1793. if d.IntPart() != testCase.IntPart {
  1794. t.Errorf("expect %d, got %d", testCase.IntPart, d.IntPart())
  1795. }
  1796. }
  1797. }
  1798. func TestBigInt(t *testing.T) {
  1799. testCases := []struct {
  1800. Dec string
  1801. BigIntRep string
  1802. }{
  1803. {"0.0", "0"},
  1804. {"0.00000", "0"},
  1805. {"0.01", "0"},
  1806. {"12.1", "12"},
  1807. {"9999.999", "9999"},
  1808. {"-32768.01234", "-32768"},
  1809. {"-572372.0000000001", "-572372"},
  1810. }
  1811. for _, testCase := range testCases {
  1812. d, err := NewFromString(testCase.Dec)
  1813. if err != nil {
  1814. t.Fatal(err)
  1815. }
  1816. if d.BigInt().String() != testCase.BigIntRep {
  1817. t.Errorf("expect %s, got %s", testCase.BigIntRep, d.BigInt())
  1818. }
  1819. }
  1820. }
  1821. func TestBigFloat(t *testing.T) {
  1822. testCases := []struct {
  1823. Dec string
  1824. BigFloatRep string
  1825. }{
  1826. {"0.0", "0"},
  1827. {"0.00000", "0"},
  1828. {"0.01", "0.01"},
  1829. {"12.1", "12.1"},
  1830. {"9999.999", "9999.999"},
  1831. {"-32768.01234", "-32768.01234"},
  1832. {"-572372.0000000001", "-572372"},
  1833. {"512.012345123451234512345", "512.0123451"},
  1834. {"1.010101010101010101010101010101", "1.01010101"},
  1835. {"55555555.555555555555555555555", "55555555.56"},
  1836. }
  1837. for _, testCase := range testCases {
  1838. d, err := NewFromString(testCase.Dec)
  1839. if err != nil {
  1840. t.Fatal(err)
  1841. }
  1842. if d.BigFloat().String() != testCase.BigFloatRep {
  1843. t.Errorf("expect %s, got %s", testCase.BigFloatRep, d.BigFloat())
  1844. }
  1845. }
  1846. }
  1847. func TestDecimal_Min(t *testing.T) {
  1848. // the first element in the array is the expected answer, rest are inputs
  1849. testCases := [][]float64{
  1850. {0, 0},
  1851. {1, 1},
  1852. {-1, -1},
  1853. {1, 1, 2},
  1854. {-2, 1, 2, -2},
  1855. {-3, 0, 2, -2, -3},
  1856. }
  1857. for _, test := range testCases {
  1858. expected, input := test[0], test[1:]
  1859. expectedDecimal := NewFromFloat(expected)
  1860. decimalInput := []Decimal{}
  1861. for _, inp := range input {
  1862. d := NewFromFloat(inp)
  1863. decimalInput = append(decimalInput, d)
  1864. }
  1865. got := Min(decimalInput[0], decimalInput[1:]...)
  1866. if !got.Equal(expectedDecimal) {
  1867. t.Errorf("Expected %v, got %v, input=%+v", expectedDecimal, got,
  1868. decimalInput)
  1869. }
  1870. }
  1871. }
  1872. func TestDecimal_Max(t *testing.T) {
  1873. // the first element in the array is the expected answer, rest are inputs
  1874. testCases := [][]float64{
  1875. {0, 0},
  1876. {1, 1},
  1877. {-1, -1},
  1878. {2, 1, 2},
  1879. {2, 1, 2, -2},
  1880. {3, 0, 3, -2},
  1881. {-2, -3, -2},
  1882. }
  1883. for _, test := range testCases {
  1884. expected, input := test[0], test[1:]
  1885. expectedDecimal := NewFromFloat(expected)
  1886. decimalInput := []Decimal{}
  1887. for _, inp := range input {
  1888. d := NewFromFloat(inp)
  1889. decimalInput = append(decimalInput, d)
  1890. }
  1891. got := Max(decimalInput[0], decimalInput[1:]...)
  1892. if !got.Equal(expectedDecimal) {
  1893. t.Errorf("Expected %v, got %v, input=%+v", expectedDecimal, got,
  1894. decimalInput)
  1895. }
  1896. }
  1897. }
  1898. func TestDecimal_Scan(t *testing.T) {
  1899. // test the Scan method that implements the
  1900. // sql.Scanner interface
  1901. // check for the for different type of values
  1902. // that are possible to be received from the database
  1903. // drivers
  1904. // in normal operations the db driver (sqlite at least)
  1905. // will return an int64 if you specified a numeric format
  1906. a := Decimal{}
  1907. dbvalue := 54.33
  1908. expected := NewFromFloat(dbvalue)
  1909. err := a.Scan(dbvalue)
  1910. if err != nil {
  1911. // Scan failed... no need to test result value
  1912. t.Errorf("a.Scan(54.33) failed with message: %s", err)
  1913. } else {
  1914. // Scan succeeded... test resulting values
  1915. if !a.Equal(expected) {
  1916. t.Errorf("%s does not equal to %s", a, expected)
  1917. }
  1918. }
  1919. // apparently MySQL 5.7.16 and returns these as float32 so we need
  1920. // to handle these as well
  1921. dbvalueFloat32 := float32(54.33)
  1922. expected = NewFromFloat(float64(dbvalueFloat32))
  1923. err = a.Scan(dbvalueFloat32)
  1924. if err != nil {
  1925. // Scan failed... no need to test result value
  1926. t.Errorf("a.Scan(54.33) failed with message: %s", err)
  1927. } else {
  1928. // Scan succeeded... test resulting values
  1929. if !a.Equal(expected) {
  1930. t.Errorf("%s does not equal to %s", a, expected)
  1931. }
  1932. }
  1933. // at least SQLite returns an int64 when 0 is stored in the db
  1934. // and you specified a numeric format on the schema
  1935. dbvalueInt := int64(0)
  1936. expected = New(dbvalueInt, 0)
  1937. err = a.Scan(dbvalueInt)
  1938. if err != nil {
  1939. // Scan failed... no need to test result value
  1940. t.Errorf("a.Scan(0) failed with message: %s", err)
  1941. } else {
  1942. // Scan succeeded... test resulting values
  1943. if !a.Equal(expected) {
  1944. t.Errorf("%s does not equal to %s", a, expected)
  1945. }
  1946. }
  1947. // in case you specified a varchar in your SQL schema,
  1948. // the database driver will return byte slice []byte
  1949. valueStr := "535.666"
  1950. dbvalueStr := []byte(valueStr)
  1951. expected, err = NewFromString(valueStr)
  1952. if err != nil {
  1953. t.Fatal(err)
  1954. }
  1955. err = a.Scan(dbvalueStr)
  1956. if err != nil {
  1957. // Scan failed... no need to test result value
  1958. t.Errorf("a.Scan('535.666') failed with message: %s", err)
  1959. } else {
  1960. // Scan succeeded... test resulting values
  1961. if !a.Equal(expected) {
  1962. t.Errorf("%s does not equal to %s", a, expected)
  1963. }
  1964. }
  1965. // lib/pq can also return strings
  1966. expected, err = NewFromString(valueStr)
  1967. if err != nil {
  1968. t.Fatal(err)
  1969. }
  1970. err = a.Scan(valueStr)
  1971. if err != nil {
  1972. // Scan failed... no need to test result value
  1973. t.Errorf("a.Scan('535.666') failed with message: %s", err)
  1974. } else {
  1975. // Scan succeeded... test resulting values
  1976. if !a.Equal(expected) {
  1977. t.Errorf("%s does not equal to %s", a, expected)
  1978. }
  1979. }
  1980. type foo struct{}
  1981. err = a.Scan(foo{})
  1982. if err == nil {
  1983. t.Errorf("a.Scan(Foo{}) should have thrown an error but did not")
  1984. }
  1985. }
  1986. func TestDecimal_Value(t *testing.T) {
  1987. // Make sure this does implement the database/sql's driver.Valuer interface
  1988. var d Decimal
  1989. if _, ok := interface{}(d).(driver.Valuer); !ok {
  1990. t.Error("Decimal does not implement driver.Valuer")
  1991. }
  1992. // check that normal case is handled appropriately
  1993. a := New(1234, -2)
  1994. expected := "12.34"
  1995. value, err := a.Value()
  1996. if err != nil {
  1997. t.Errorf("Decimal(12.34).Value() failed with message: %s", err)
  1998. } else if value.(string) != expected {
  1999. t.Errorf("%s does not equal to %s", a, expected)
  2000. }
  2001. }
  2002. // old tests after this line
  2003. func TestDecimal_Scale(t *testing.T) {
  2004. a := New(1234, -3)
  2005. if a.Exponent() != -3 {
  2006. t.Errorf("error")
  2007. }
  2008. }
  2009. func TestDecimal_Abs1(t *testing.T) {
  2010. a := New(-1234, -4)
  2011. b := New(1234, -4)
  2012. c := a.Abs()
  2013. if c.Cmp(b) != 0 {
  2014. t.Errorf("error")
  2015. }
  2016. }
  2017. func TestDecimal_Abs2(t *testing.T) {
  2018. a := New(-1234, -4)
  2019. b := New(1234, -4)
  2020. c := b.Abs()
  2021. if c.Cmp(a) == 0 {
  2022. t.Errorf("error")
  2023. }
  2024. }
  2025. func TestDecimal_Equalities(t *testing.T) {
  2026. a := New(1234, 3)
  2027. b := New(1234, 3)
  2028. c := New(1234, 4)
  2029. if !a.Equal(b) {
  2030. t.Errorf("%q should equal %q", a, b)
  2031. }
  2032. if a.Equal(c) {
  2033. t.Errorf("%q should not equal %q", a, c)
  2034. }
  2035. // note, this block should be deprecated, here for backwards compatibility
  2036. if !a.Equals(b) {
  2037. t.Errorf("%q should equal %q", a, b)
  2038. }
  2039. if !c.GreaterThan(b) {
  2040. t.Errorf("%q should be greater than %q", c, b)
  2041. }
  2042. if b.GreaterThan(c) {
  2043. t.Errorf("%q should not be greater than %q", b, c)
  2044. }
  2045. if !a.GreaterThanOrEqual(b) {
  2046. t.Errorf("%q should be greater or equal %q", a, b)
  2047. }
  2048. if !c.GreaterThanOrEqual(b) {
  2049. t.Errorf("%q should be greater or equal %q", c, b)
  2050. }
  2051. if b.GreaterThanOrEqual(c) {
  2052. t.Errorf("%q should not be greater or equal %q", b, c)
  2053. }
  2054. if !b.LessThan(c) {
  2055. t.Errorf("%q should be less than %q", a, b)
  2056. }
  2057. if c.LessThan(b) {
  2058. t.Errorf("%q should not be less than %q", a, b)
  2059. }
  2060. if !a.LessThanOrEqual(b) {
  2061. t.Errorf("%q should be less than or equal %q", a, b)
  2062. }
  2063. if !b.LessThanOrEqual(c) {
  2064. t.Errorf("%q should be less than or equal %q", a, b)
  2065. }
  2066. if c.LessThanOrEqual(b) {
  2067. t.Errorf("%q should not be less than or equal %q", a, b)
  2068. }
  2069. }
  2070. func TestDecimal_ScalesNotEqual(t *testing.T) {
  2071. a := New(1234, 2)
  2072. b := New(1234, 3)
  2073. if a.Equal(b) {
  2074. t.Errorf("%q should not equal %q", a, b)
  2075. }
  2076. }
  2077. func TestDecimal_Cmp1(t *testing.T) {
  2078. a := New(123, 3)
  2079. b := New(-1234, 2)
  2080. if a.Cmp(b) != 1 {
  2081. t.Errorf("Error")
  2082. }
  2083. }
  2084. func TestDecimal_Cmp2(t *testing.T) {
  2085. a := New(123, 3)
  2086. b := New(1234, 2)
  2087. if a.Cmp(b) != -1 {
  2088. t.Errorf("Error")
  2089. }
  2090. }
  2091. func TestPow(t *testing.T) {
  2092. a := New(4, 0)
  2093. b := New(2, 0)
  2094. x := a.Pow(b)
  2095. if x.String() != "16" {
  2096. t.Errorf("Error, saw %s", x.String())
  2097. }
  2098. }
  2099. func TestNegativePow(t *testing.T) {
  2100. a := New(4, 0)
  2101. b := New(-2, 0)
  2102. x := a.Pow(b)
  2103. if x.String() != "0.0625" {
  2104. t.Errorf("Error, saw %s", x.String())
  2105. }
  2106. }
  2107. func TestDecimal_IsInteger(t *testing.T) {
  2108. for _, testCase := range []struct {
  2109. Dec string
  2110. IsInteger bool
  2111. }{
  2112. {"0", true},
  2113. {"0.0000", true},
  2114. {"0.01", false},
  2115. {"0.01010101010000", false},
  2116. {"12.0", true},
  2117. {"12.00000000000000", true},
  2118. {"12.10000", false},
  2119. {"9999.0000", true},
  2120. {"99999999.000000000", true},
  2121. {"-656323444.0000000000000", true},
  2122. {"-32768.01234", false},
  2123. {"-32768.0123423562623600000", false},
  2124. } {
  2125. d, err := NewFromString(testCase.Dec)
  2126. if err != nil {
  2127. t.Fatal(err)
  2128. }
  2129. if d.IsInteger() != testCase.IsInteger {
  2130. t.Errorf("expect %t, got %t, for %s", testCase.IsInteger, d.IsInteger(), testCase.Dec)
  2131. }
  2132. }
  2133. }
  2134. func TestDecimal_Sign(t *testing.T) {
  2135. if Zero.Sign() != 0 {
  2136. t.Errorf("%q should have sign 0", Zero)
  2137. }
  2138. one := New(1, 0)
  2139. if one.Sign() != 1 {
  2140. t.Errorf("%q should have sign 1", one)
  2141. }
  2142. mone := New(-1, 0)
  2143. if mone.Sign() != -1 {
  2144. t.Errorf("%q should have sign -1", mone)
  2145. }
  2146. }
  2147. func didPanic(f func()) bool {
  2148. ret := false
  2149. func() {
  2150. defer func() {
  2151. if message := recover(); message != nil {
  2152. ret = true
  2153. }
  2154. }()
  2155. // call the target function
  2156. f()
  2157. }()
  2158. return ret
  2159. }
  2160. func TestDecimal_Coefficient(t *testing.T) {
  2161. d := New(123, 0)
  2162. co := d.Coefficient()
  2163. if co.Int64() != 123 {
  2164. t.Error("Coefficient should be 123; Got:", co)
  2165. }
  2166. co.Set(big.NewInt(0))
  2167. if d.IntPart() != 123 {
  2168. t.Error("Modifying coefficient modified Decimal; Got:", d)
  2169. }
  2170. }
  2171. func TestNullDecimal_Scan(t *testing.T) {
  2172. // test the Scan method that implements the
  2173. // sql.Scanner interface
  2174. // check for the for different type of values
  2175. // that are possible to be received from the database
  2176. // drivers
  2177. // in normal operations the db driver (sqlite at least)
  2178. // will return an int64 if you specified a numeric format
  2179. // Make sure handles nil values
  2180. a := NullDecimal{}
  2181. var dbvaluePtr interface{}
  2182. err := a.Scan(dbvaluePtr)
  2183. if err != nil {
  2184. // Scan failed... no need to test result value
  2185. t.Errorf("a.Scan(nil) failed with message: %s", err)
  2186. } else {
  2187. if a.Valid {
  2188. t.Errorf("%s is not null", a.Decimal)
  2189. }
  2190. }
  2191. dbvalue := 54.33
  2192. expected := NewFromFloat(dbvalue)
  2193. err = a.Scan(dbvalue)
  2194. if err != nil {
  2195. // Scan failed... no need to test result value
  2196. t.Errorf("a.Scan(54.33) failed with message: %s", err)
  2197. } else {
  2198. // Scan succeeded... test resulting values
  2199. if !a.Valid {
  2200. t.Errorf("%s is null", a.Decimal)
  2201. } else if !a.Decimal.Equals(expected) {
  2202. t.Errorf("%s does not equal to %s", a.Decimal, expected)
  2203. }
  2204. }
  2205. // at least SQLite returns an int64 when 0 is stored in the db
  2206. // and you specified a numeric format on the schema
  2207. dbvalueInt := int64(0)
  2208. expected = New(dbvalueInt, 0)
  2209. err = a.Scan(dbvalueInt)
  2210. if err != nil {
  2211. // Scan failed... no need to test result value
  2212. t.Errorf("a.Scan(0) failed with message: %s", err)
  2213. } else {
  2214. // Scan succeeded... test resulting values
  2215. if !a.Valid {
  2216. t.Errorf("%s is null", a.Decimal)
  2217. } else if !a.Decimal.Equals(expected) {
  2218. t.Errorf("%v does not equal %v", a, expected)
  2219. }
  2220. }
  2221. // in case you specified a varchar in your SQL schema,
  2222. // the database driver will return byte slice []byte
  2223. valueStr := "535.666"
  2224. dbvalueStr := []byte(valueStr)
  2225. expected, err = NewFromString(valueStr)
  2226. if err != nil {
  2227. t.Fatal(err)
  2228. }
  2229. err = a.Scan(dbvalueStr)
  2230. if err != nil {
  2231. // Scan failed... no need to test result value
  2232. t.Errorf("a.Scan('535.666') failed with message: %s", err)
  2233. } else {
  2234. // Scan succeeded... test resulting values
  2235. if !a.Valid {
  2236. t.Errorf("%s is null", a.Decimal)
  2237. } else if !a.Decimal.Equals(expected) {
  2238. t.Errorf("%v does not equal %v", a, expected)
  2239. }
  2240. }
  2241. // lib/pq can also return strings
  2242. expected, err = NewFromString(valueStr)
  2243. if err != nil {
  2244. t.Fatal(err)
  2245. }
  2246. err = a.Scan(valueStr)
  2247. if err != nil {
  2248. // Scan failed... no need to test result value
  2249. t.Errorf("a.Scan('535.666') failed with message: %s", err)
  2250. } else {
  2251. // Scan succeeded... test resulting values
  2252. if !a.Valid {
  2253. t.Errorf("%s is null", a.Decimal)
  2254. } else if !a.Decimal.Equals(expected) {
  2255. t.Errorf("%v does not equal %v", a, expected)
  2256. }
  2257. }
  2258. }
  2259. func TestNullDecimal_Value(t *testing.T) {
  2260. // Make sure this does implement the database/sql's driver.Valuer interface
  2261. var nullDecimal NullDecimal
  2262. if _, ok := interface{}(nullDecimal).(driver.Valuer); !ok {
  2263. t.Error("NullDecimal does not implement driver.Valuer")
  2264. }
  2265. // check that null is handled appropriately
  2266. value, err := nullDecimal.Value()
  2267. if err != nil {
  2268. t.Errorf("NullDecimal{}.Valid() failed with message: %s", err)
  2269. } else if value != nil {
  2270. t.Errorf("%v is not nil", value)
  2271. }
  2272. // check that normal case is handled appropriately
  2273. a := NullDecimal{Decimal: New(1234, -2), Valid: true}
  2274. expected := "12.34"
  2275. value, err = a.Value()
  2276. if err != nil {
  2277. t.Errorf("NullDecimal(12.34).Value() failed with message: %s", err)
  2278. } else if value.(string) != expected {
  2279. t.Errorf("%v does not equal %v", a, expected)
  2280. }
  2281. }
  2282. func TestBinary(t *testing.T) {
  2283. for _, y := range testTable {
  2284. x := y.float
  2285. // Create the decimal
  2286. d1 := NewFromFloat(x)
  2287. // Encode to binary
  2288. b, err := d1.MarshalBinary()
  2289. if err != nil {
  2290. t.Errorf("error marshalling %v to binary: %v", d1, err)
  2291. }
  2292. // Restore from binary
  2293. var d2 Decimal
  2294. err = (&d2).UnmarshalBinary(b)
  2295. if err != nil {
  2296. t.Errorf("error unmarshalling from binary: %v", err)
  2297. }
  2298. // The restored decimal should equal the original
  2299. if !d1.Equals(d2) {
  2300. t.Errorf("expected %v when restoring, got %v", d1, d2)
  2301. }
  2302. }
  2303. }
  2304. func slicesEqual(a, b []byte) bool {
  2305. for i, val := range a {
  2306. if b[i] != val {
  2307. return false
  2308. }
  2309. }
  2310. return true
  2311. }
  2312. func TestGobEncode(t *testing.T) {
  2313. for _, y := range testTable {
  2314. x := y.float
  2315. d1 := NewFromFloat(x)
  2316. b1, err := d1.GobEncode()
  2317. if err != nil {
  2318. t.Errorf("error encoding %v to binary: %v", d1, err)
  2319. }
  2320. d2 := NewFromFloat(x)
  2321. b2, err := d2.GobEncode()
  2322. if err != nil {
  2323. t.Errorf("error encoding %v to binary: %v", d2, err)
  2324. }
  2325. if !slicesEqual(b1, b2) {
  2326. t.Errorf("something about the gobencode is not working properly \n%v\n%v", b1, b2)
  2327. }
  2328. var d3 Decimal
  2329. err = d3.GobDecode(b1)
  2330. if err != nil {
  2331. t.Errorf("Error gobdecoding %v, got %v", b1, d3)
  2332. }
  2333. var d4 Decimal
  2334. err = d4.GobDecode(b2)
  2335. if err != nil {
  2336. t.Errorf("Error gobdecoding %v, got %v", b2, d4)
  2337. }
  2338. eq := d3.Equal(d4)
  2339. if eq != true {
  2340. t.Errorf("Encoding then decoding mutated Decimal")
  2341. }
  2342. eq = d1.Equal(d3)
  2343. if eq != true {
  2344. t.Errorf("Error gobencoding/decoding %v, got %v", d1, d3)
  2345. }
  2346. }
  2347. }
  2348. func TestSum(t *testing.T) {
  2349. vals := make([]Decimal, 10)
  2350. var i = int64(0)
  2351. for key := range vals {
  2352. vals[key] = New(i, 0)
  2353. i++
  2354. }
  2355. sum := Sum(vals[0], vals[1:]...)
  2356. if !sum.Equal(New(45, 0)) {
  2357. t.Errorf("Failed to calculate sum, expected %s got %s", New(45, 0), sum)
  2358. }
  2359. }
  2360. func TestAvg(t *testing.T) {
  2361. vals := make([]Decimal, 10)
  2362. var i = int64(0)
  2363. for key := range vals {
  2364. vals[key] = New(i, 0)
  2365. i++
  2366. }
  2367. avg := Avg(vals[0], vals[1:]...)
  2368. if !avg.Equal(NewFromFloat(4.5)) {
  2369. t.Errorf("Failed to calculate average, expected %s got %s", NewFromFloat(4.5).String(), avg.String())
  2370. }
  2371. }
  2372. func TestRoundBankAnomaly(t *testing.T) {
  2373. a := New(25, -1)
  2374. b := New(250, -2)
  2375. if !a.Equal(b) {
  2376. t.Errorf("Expected %s to equal %s", a, b)
  2377. }
  2378. expected := New(2, 0)
  2379. aRounded := a.RoundBank(0)
  2380. if !aRounded.Equal(expected) {
  2381. t.Errorf("Expected bank rounding %s to equal %s, but it was %s", a, expected, aRounded)
  2382. }
  2383. bRounded := b.RoundBank(0)
  2384. if !bRounded.Equal(expected) {
  2385. t.Errorf("Expected bank rounding %s to equal %s, but it was %s", b, expected, bRounded)
  2386. }
  2387. }
  2388. // Trig tests
  2389. // For Atan
  2390. func TestAtan(t *testing.T) {
  2391. inps := []string{
  2392. "-2.91919191919191919",
  2393. "-1.0",
  2394. "-0.25",
  2395. "0.0",
  2396. "0.33",
  2397. "1.0",
  2398. "5.0",
  2399. "10",
  2400. "11000020.2407442310156021090304691671842603586882014729198302312846062338790031898128063403419218957424",
  2401. }
  2402. sols := []string{
  2403. "-1.24076438822058001027437062753106",
  2404. "-0.78539816339744833061616997868383",
  2405. "-0.24497866312686415",
  2406. "0.0",
  2407. "0.318747560420644443",
  2408. "0.78539816339744833061616997868383",
  2409. "1.37340076694501580123233995736766",
  2410. "1.47112767430373453123233995736766",
  2411. "1.57079623588597296123259450235374",
  2412. }
  2413. for i, inp := range inps {
  2414. d, err := NewFromString(inp)
  2415. if err != nil {
  2416. t.FailNow()
  2417. }
  2418. s, err := NewFromString(sols[i])
  2419. if err != nil {
  2420. t.FailNow()
  2421. }
  2422. a := d.Atan()
  2423. if !a.Equal(s) {
  2424. t.Errorf("expected %s, got %s", s, a)
  2425. }
  2426. }
  2427. }
  2428. // For Sin
  2429. func TestSin(t *testing.T) {
  2430. inps := []string{
  2431. "-2.91919191919191919",
  2432. "-1.0",
  2433. "-0.25",
  2434. "0.0",
  2435. "0.33",
  2436. "1.0",
  2437. "5.0",
  2438. "10",
  2439. "11000020.2407442310156021090304691671842603586882014729198302312846062338790031898128063403419218957424",
  2440. }
  2441. sols := []string{"-0.22057186252002995641471297726318877448242875710373383657841216606788849153474483300147427943530288911869356126149550184271061369789963810497434594683859566879253561990821788142048867910104964466745284318577343435957806286762494529983369776697504436326725441516925396488258485248699247367113416543705253919473126183478178486954138205996912770183192357029798618739277146694040778731661407420114923656224752540889120768",
  2442. "-0.841470984807896544828551915928318375739843472469519282898610111931110319333748010828751784005573402229699531838022117989945539661588502120624574802425114599802714611508860519655182175315926637327774878594985045816542706701485174683683726979309922117859910272413672784175028365607893544855897795184024100973080880074046886009375162838756876336134083638363801171409953672944184918309063800980214873465660723218405962257950683415203634506166523593278",
  2443. "-0.2474039592545229296662577977006816864013671875",
  2444. "0",
  2445. "0.3240430283948683457891331120415701894104386268737728",
  2446. "0.841470984807896544828551915928318375739843472469519282898610111931110319333748010828751784005573402229699531838022117989945539661588502120624574802425114599802714611508860519655182175315926637327774878594985045816542706701485174683683726979309922117859910272413672784175028365607893544855897795184024100973080880074046886009375162838756876336134083638363801171409953672944184918309063800980214873465660723218405962257950683415203634506166523593278",
  2447. "-0.958924274663138409032065951037351417114444405831206421994322505831797734568720303321152847999323782235893449831846516332891972309733806145798957570823292783131379570446989311599459252931842975162373777189193072018951049969744350662993214861042908755303566670204873618202680865638534865944483058650517380292320436016362659617294570185140789829574277032406195741535138712427510938542219940873171248862329526140744770994303733112530324791184417282382",
  2448. "-0.54402111088937016772477554483765124109312606762621462357463994520238396180161585438877562935656067241573063207614488370477645194661241525080677431257416988398683714890165970942834453391033857378247849486306346743023618509617104937236345831462093934032592562972419977883837745736210439651143668255744843041350221801750331646628192115694352540293150183983357476391787825596543270240461102629075832777618592034309799936",
  2449. "-0.564291758480422881634770440632390475980828840253516895637281099241819037882007239070203007530085741820184955492382572029153491807930868879341091067301689987699567034024159005627332722089169680203292567574310010066799858914647295684974242359142300929248173166551428537696685165964880390889406578530338963341989826231514301546476672476399906348023294571001061677668735117509440368611093448917120819545826797975989350435900286332895885871219875665471968941335407351099209738417818747252638912592184093301853338763294381446907254104878969784040526201729163408095795934201105630182851806342356035203279670146684553491616847294749721014579109870396804713831114709372638323643327823671187472335866664108658093206409882794958673673978956925250261545083579947618620746006004554405785185537391110314728988164693223775249484198058394348289545771967707968288542718255197272633789792059019367104377340604030147471453833808674013259696102003732963091159662478879760121731138091114134586544668859915547568540172541576138084166990547345181184322550297604278946942918844039406876827936831612756344331500301118652183156052728447906384772901595431751550607818380262138322673253023464533931883787069611052589166000316238423939491520880451263927981787175602294299295744",
  2450. }
  2451. for i, inp := range inps {
  2452. d, err := NewFromString(inp)
  2453. if err != nil {
  2454. t.FailNow()
  2455. }
  2456. s, err := NewFromString(sols[i])
  2457. if err != nil {
  2458. t.FailNow()
  2459. }
  2460. a := d.Sin()
  2461. if !a.Equal(s) {
  2462. t.Errorf("expected %s, got %s", s, a)
  2463. }
  2464. }
  2465. }
  2466. // For Cos
  2467. func TestCos(t *testing.T) {
  2468. inps := []string{
  2469. "-2.91919191919191919",
  2470. "-1.0",
  2471. "-0.25",
  2472. "0.0",
  2473. "0.33",
  2474. "1.0",
  2475. "5.0",
  2476. "10",
  2477. "11000020.2407442310156021090304691671842603586882014729198302312846062338790031898128063403419218957424",
  2478. }
  2479. sols := []string{
  2480. "-0.975370726167463467746508538219884948528729295145689640359666742268127382748782064668565276308334226452812521220478854320025773591423493734486361306323829818426063430805234608660356853863442937297855742231573288105774823103008774355455799906250461848079705023428527473474556899228935370709945979509634251305018978306493011197513482210179171510947538040406781879762352211326273272515279567525396877609653501706919545667682725671944948392322552266752",
  2481. "0.54030230586813965874561515067176071767603141150991567490927772778673118786033739102174242337864109186439207498973007363884202112942385976796862442063752663646870430360736682397798633852405003167527051283327366631405990604840629657123985368031838052877290142895506386796217551784101265975360960112885444847880134909594560331781699767647860744559228420471946006511861233129745921297270844542687374552066388998112901504",
  2482. "0.968912421710644784099084544806854121387004852294921875",
  2483. "1",
  2484. "0.9460423435283869715490383692051286742343482760977712222",
  2485. "0.54030230586813965874561515067176071767603141150991567490927772778673118786033739102174242337864109186439207498973007363884202112942385976796862442063752663646870430360736682397798633852405003167527051283327366631405990604840629657123985368031838052877290142895506386796217551784101265975360960112885444847880134909594560331781699767647860744559228420471946006511861233129745921297270844542687374552066388998112901504",
  2486. "0.28366218546322646623291670213892426815646045792775066552057877370468842342090306560693620285882975471913545189522117672866861003904575909174769890684057564495184019705963607555427518763375472432216131070235796577209064861003009894615394882021220247535890708789312783718414424224334988974848162884228012265684775651099758365989567444515619764427493598258393280941942356912304265535918025036942025858493361644535438208",
  2487. "-0.839071529076452222947082170022504835457755803801719612447629165523199043803440231769716865070163209041973184176293170330332317060558438085478980463542480791358920580076809381102480339018809694514100495572097422057215638383077242523713704127605770444906854175870243452753002238589530499630034663296166308443155999957196346563161387705205277189957388653461251461388391745795979375660087266037741360406956289962327970672363315696841378765492754546688",
  2488. "-0.82557544253149396284458404188071504476091346830440347376462206521981928020803354950315062147200396866217255527509254080721982393941347365824137698491042935894213870423296625749297033966815252917361266452901192457318047750698424190124169875103436588397415032138037063155981648677895645409699825582226442363080800781881653440538927704569142007751338851079530521979429507520541625303794665680584709171813053216867014700596866196844144286737568957809383224972108999354839705480223052622003994027222120126949093911643497423100187973906980635670000034664323357488815820848035808846624518774608931622703631130673844138378087837990739103263093532314835289302930152150130664948083902949999427848344301686172490282395687167681679607401220592559832932068966455384902377056623736013617949634746332323529256184776892339963173795176200590119077305668901887229709592836744082027738666294887303249770621722032438202753270710379312736193201366287952361100525126056993039858894987153270630277483613793395809214871734783742285495171911648254647287555645360520115341268930844095156502348405343740866836850201634640011708462641462047870611041595707018966032206807675586825362640000739202116391403514629284000986232673698892843586989003952425039512325844566790376383098534975022847888104706525937115931692008959513984157709954859352131323440787667052399474107219968",
  2489. }
  2490. for i, inp := range inps {
  2491. d, err := NewFromString(inp)
  2492. if err != nil {
  2493. t.FailNow()
  2494. }
  2495. s, err := NewFromString(sols[i])
  2496. if err != nil {
  2497. t.FailNow()
  2498. }
  2499. a := d.Cos()
  2500. if !a.Equal(s) {
  2501. t.Errorf("expected %s, got %s", s, a)
  2502. }
  2503. }
  2504. }
  2505. // For Tan
  2506. func TestTan(t *testing.T) {
  2507. inps := []string{
  2508. "-2.91919191919191919",
  2509. "-1.0",
  2510. "-0.25",
  2511. "0.0",
  2512. "0.33",
  2513. "1.0",
  2514. "5.0",
  2515. "10",
  2516. "11000020.2407442310156021090304691671842603586882014729198302312846062338790031898128063403419218957424",
  2517. }
  2518. sols := []string{
  2519. "0.2261415650505790298980791606748881031998682652",
  2520. "-1.5574077246549025",
  2521. "-0.255341921221036275",
  2522. "0.0",
  2523. "0.342524867530038963",
  2524. "1.5574077246549025",
  2525. "-3.3805150062465829",
  2526. "0.6483608274590872485524085572681343280321117494",
  2527. "0.68351325561491170753499935023939368502774607234006019034769919811202010905597996164029250820702097041244539696",
  2528. }
  2529. for i, inp := range inps {
  2530. d, err := NewFromString(inp)
  2531. if err != nil {
  2532. t.FailNow()
  2533. }
  2534. s, err := NewFromString(sols[i])
  2535. if err != nil {
  2536. t.FailNow()
  2537. }
  2538. a := d.Tan()
  2539. if !a.Equal(s) {
  2540. t.Errorf("expected %s, got %s", s, a)
  2541. }
  2542. }
  2543. }
  2544. func ExampleNewFromFloat32() {
  2545. fmt.Println(NewFromFloat32(123.123123123123).String())
  2546. fmt.Println(NewFromFloat32(.123123123123123).String())
  2547. fmt.Println(NewFromFloat32(-1e13).String())
  2548. // OUTPUT:
  2549. //123.12312
  2550. //0.123123124
  2551. //-10000000000000
  2552. }
  2553. func ExampleNewFromFloat() {
  2554. fmt.Println(NewFromFloat(123.123123123123).String())
  2555. fmt.Println(NewFromFloat(.123123123123123).String())
  2556. fmt.Println(NewFromFloat(-1e13).String())
  2557. // OUTPUT:
  2558. //123.123123123123
  2559. //0.123123123123123
  2560. //-10000000000000
  2561. }