decimal.go 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593
  1. // Package decimal implements an arbitrary precision fixed-point decimal.
  2. //
  3. // The zero-value of a Decimal is 0, as you would expect.
  4. //
  5. // The best way to create a new Decimal is to use decimal.NewFromString, ex:
  6. //
  7. // n, err := decimal.NewFromString("-123.4567")
  8. // n.String() // output: "-123.4567"
  9. //
  10. // To use Decimal as part of a struct:
  11. //
  12. // type Struct struct {
  13. // Number Decimal
  14. // }
  15. //
  16. // Note: This can "only" represent numbers with a maximum of 2^31 digits after the decimal point.
  17. package decimal
  18. import (
  19. "database/sql/driver"
  20. "encoding/binary"
  21. "fmt"
  22. "math"
  23. "math/big"
  24. "regexp"
  25. "strconv"
  26. "strings"
  27. )
  28. // DivisionPrecision is the number of decimal places in the result when it
  29. // doesn't divide exactly.
  30. //
  31. // Example:
  32. //
  33. // d1 := decimal.NewFromFloat(2).Div(decimal.NewFromFloat(3))
  34. // d1.String() // output: "0.6666666666666667"
  35. // d2 := decimal.NewFromFloat(2).Div(decimal.NewFromFloat(30000))
  36. // d2.String() // output: "0.0000666666666667"
  37. // d3 := decimal.NewFromFloat(20000).Div(decimal.NewFromFloat(3))
  38. // d3.String() // output: "6666.6666666666666667"
  39. // decimal.DivisionPrecision = 3
  40. // d4 := decimal.NewFromFloat(2).Div(decimal.NewFromFloat(3))
  41. // d4.String() // output: "0.667"
  42. //
  43. var DivisionPrecision = 16
  44. // MarshalJSONWithoutQuotes should be set to true if you want the decimal to
  45. // be JSON marshaled as a number, instead of as a string.
  46. // WARNING: this is dangerous for decimals with many digits, since many JSON
  47. // unmarshallers (ex: Javascript's) will unmarshal JSON numbers to IEEE 754
  48. // double-precision floating point numbers, which means you can potentially
  49. // silently lose precision.
  50. var MarshalJSONWithoutQuotes = false
  51. // Zero constant, to make computations faster.
  52. // Zero should never be compared with == or != directly, please use decimal.Equal or decimal.Cmp instead.
  53. var Zero = New(0, 1)
  54. var zeroInt = big.NewInt(0)
  55. var oneInt = big.NewInt(1)
  56. var twoInt = big.NewInt(2)
  57. var fourInt = big.NewInt(4)
  58. var fiveInt = big.NewInt(5)
  59. var tenInt = big.NewInt(10)
  60. var twentyInt = big.NewInt(20)
  61. // Decimal represents a fixed-point decimal. It is immutable.
  62. // number = value * 10 ^ exp
  63. type Decimal struct {
  64. value *big.Int
  65. // NOTE(vadim): this must be an int32, because we cast it to float64 during
  66. // calculations. If exp is 64 bit, we might lose precision.
  67. // If we cared about being able to represent every possible decimal, we
  68. // could make exp a *big.Int but it would hurt performance and numbers
  69. // like that are unrealistic.
  70. exp int32
  71. }
  72. // New returns a new fixed-point decimal, value * 10 ^ exp.
  73. func New(value int64, exp int32) Decimal {
  74. return Decimal{
  75. value: big.NewInt(value),
  76. exp: exp,
  77. }
  78. }
  79. // NewFromInt converts a int64 to Decimal.
  80. //
  81. // Example:
  82. //
  83. // NewFromInt(123).String() // output: "123"
  84. // NewFromInt(-10).String() // output: "-10"
  85. func NewFromInt(value int64) Decimal {
  86. return Decimal{
  87. value: big.NewInt(value),
  88. exp: 0,
  89. }
  90. }
  91. // NewFromInt32 converts a int32 to Decimal.
  92. //
  93. // Example:
  94. //
  95. // NewFromInt(123).String() // output: "123"
  96. // NewFromInt(-10).String() // output: "-10"
  97. func NewFromInt32(value int32) Decimal {
  98. return Decimal{
  99. value: big.NewInt(int64(value)),
  100. exp: 0,
  101. }
  102. }
  103. // NewFromBigInt returns a new Decimal from a big.Int, value * 10 ^ exp
  104. func NewFromBigInt(value *big.Int, exp int32) Decimal {
  105. return Decimal{
  106. value: big.NewInt(0).Set(value),
  107. exp: exp,
  108. }
  109. }
  110. // NewFromString returns a new Decimal from a string representation.
  111. // Trailing zeroes are not trimmed.
  112. //
  113. // Example:
  114. //
  115. // d, err := NewFromString("-123.45")
  116. // d2, err := NewFromString(".0001")
  117. // d3, err := NewFromString("1.47000")
  118. //
  119. func NewFromString(value string) (Decimal, error) {
  120. originalInput := value
  121. var intString string
  122. var exp int64
  123. // Check if number is using scientific notation
  124. eIndex := strings.IndexAny(value, "Ee")
  125. if eIndex != -1 {
  126. expInt, err := strconv.ParseInt(value[eIndex+1:], 10, 32)
  127. if err != nil {
  128. if e, ok := err.(*strconv.NumError); ok && e.Err == strconv.ErrRange {
  129. return Decimal{}, fmt.Errorf("can't convert %s to decimal: fractional part too long", value)
  130. }
  131. return Decimal{}, fmt.Errorf("can't convert %s to decimal: exponent is not numeric", value)
  132. }
  133. value = value[:eIndex]
  134. exp = expInt
  135. }
  136. pIndex := -1
  137. vLen := len(value)
  138. for i := 0; i < vLen; i++ {
  139. if value[i] == '.' {
  140. if pIndex > -1 {
  141. return Decimal{}, fmt.Errorf("can't convert %s to decimal: too many .s", value)
  142. }
  143. pIndex = i
  144. }
  145. }
  146. if pIndex == -1 {
  147. // There is no decimal point, we can just parse the original string as
  148. // an int
  149. intString = value
  150. } else {
  151. if pIndex+1 < vLen {
  152. intString = value[:pIndex] + value[pIndex+1:]
  153. } else {
  154. intString = value[:pIndex]
  155. }
  156. expInt := -len(value[pIndex+1:])
  157. exp += int64(expInt)
  158. }
  159. var dValue *big.Int
  160. // strconv.ParseInt is faster than new(big.Int).SetString so this is just a shortcut for strings we know won't overflow
  161. if len(intString) <= 18 {
  162. parsed64, err := strconv.ParseInt(intString, 10, 64)
  163. if err != nil {
  164. return Decimal{}, fmt.Errorf("can't convert %s to decimal", value)
  165. }
  166. dValue = big.NewInt(parsed64)
  167. } else {
  168. dValue = new(big.Int)
  169. _, ok := dValue.SetString(intString, 10)
  170. if !ok {
  171. return Decimal{}, fmt.Errorf("can't convert %s to decimal", value)
  172. }
  173. }
  174. if exp < math.MinInt32 || exp > math.MaxInt32 {
  175. // NOTE(vadim): I doubt a string could realistically be this long
  176. return Decimal{}, fmt.Errorf("can't convert %s to decimal: fractional part too long", originalInput)
  177. }
  178. return Decimal{
  179. value: dValue,
  180. exp: int32(exp),
  181. }, nil
  182. }
  183. // NewFromFormattedString returns a new Decimal from a formatted string representation.
  184. // The second argument - replRegexp, is a regular expression that is used to find characters that should be
  185. // removed from given decimal string representation. All matched characters will be replaced with an empty string.
  186. //
  187. // Example:
  188. //
  189. // r := regexp.MustCompile("[$,]")
  190. // d1, err := NewFromFormattedString("$5,125.99", r)
  191. //
  192. // r2 := regexp.MustCompile("[_]")
  193. // d2, err := NewFromFormattedString("1_000_000", r2)
  194. //
  195. // r3 := regexp.MustCompile("[USD\\s]")
  196. // d3, err := NewFromFormattedString("5000 USD", r3)
  197. //
  198. func NewFromFormattedString(value string, replRegexp *regexp.Regexp) (Decimal, error) {
  199. parsedValue := replRegexp.ReplaceAllString(value, "")
  200. d, err := NewFromString(parsedValue)
  201. if err != nil {
  202. return Decimal{}, err
  203. }
  204. return d, nil
  205. }
  206. // RequireFromString returns a new Decimal from a string representation
  207. // or panics if NewFromString would have returned an error.
  208. //
  209. // Example:
  210. //
  211. // d := RequireFromString("-123.45")
  212. // d2 := RequireFromString(".0001")
  213. //
  214. func RequireFromString(value string) Decimal {
  215. dec, err := NewFromString(value)
  216. if err != nil {
  217. panic(err)
  218. }
  219. return dec
  220. }
  221. // NewFromFloat converts a float64 to Decimal.
  222. //
  223. // The converted number will contain the number of significant digits that can be
  224. // represented in a float with reliable roundtrip.
  225. // This is typically 15 digits, but may be more in some cases.
  226. // See https://www.exploringbinary.com/decimal-precision-of-binary-floating-point-numbers/ for more information.
  227. //
  228. // For slightly faster conversion, use NewFromFloatWithExponent where you can specify the precision in absolute terms.
  229. //
  230. // NOTE: this will panic on NaN, +/-inf
  231. func NewFromFloat(value float64) Decimal {
  232. if value == 0 {
  233. return New(0, 0)
  234. }
  235. return newFromFloat(value, math.Float64bits(value), &float64info)
  236. }
  237. // NewFromFloat32 converts a float32 to Decimal.
  238. //
  239. // The converted number will contain the number of significant digits that can be
  240. // represented in a float with reliable roundtrip.
  241. // This is typically 6-8 digits depending on the input.
  242. // See https://www.exploringbinary.com/decimal-precision-of-binary-floating-point-numbers/ for more information.
  243. //
  244. // For slightly faster conversion, use NewFromFloatWithExponent where you can specify the precision in absolute terms.
  245. //
  246. // NOTE: this will panic on NaN, +/-inf
  247. func NewFromFloat32(value float32) Decimal {
  248. if value == 0 {
  249. return New(0, 0)
  250. }
  251. // XOR is workaround for https://github.com/golang/go/issues/26285
  252. a := math.Float32bits(value) ^ 0x80808080
  253. return newFromFloat(float64(value), uint64(a)^0x80808080, &float32info)
  254. }
  255. func newFromFloat(val float64, bits uint64, flt *floatInfo) Decimal {
  256. if math.IsNaN(val) || math.IsInf(val, 0) {
  257. panic(fmt.Sprintf("Cannot create a Decimal from %v", val))
  258. }
  259. exp := int(bits>>flt.mantbits) & (1<<flt.expbits - 1)
  260. mant := bits & (uint64(1)<<flt.mantbits - 1)
  261. switch exp {
  262. case 0:
  263. // denormalized
  264. exp++
  265. default:
  266. // add implicit top bit
  267. mant |= uint64(1) << flt.mantbits
  268. }
  269. exp += flt.bias
  270. var d decimal
  271. d.Assign(mant)
  272. d.Shift(exp - int(flt.mantbits))
  273. d.neg = bits>>(flt.expbits+flt.mantbits) != 0
  274. roundShortest(&d, mant, exp, flt)
  275. // If less than 19 digits, we can do calculation in an int64.
  276. if d.nd < 19 {
  277. tmp := int64(0)
  278. m := int64(1)
  279. for i := d.nd - 1; i >= 0; i-- {
  280. tmp += m * int64(d.d[i]-'0')
  281. m *= 10
  282. }
  283. if d.neg {
  284. tmp *= -1
  285. }
  286. return Decimal{value: big.NewInt(tmp), exp: int32(d.dp) - int32(d.nd)}
  287. }
  288. dValue := new(big.Int)
  289. dValue, ok := dValue.SetString(string(d.d[:d.nd]), 10)
  290. if ok {
  291. return Decimal{value: dValue, exp: int32(d.dp) - int32(d.nd)}
  292. }
  293. return NewFromFloatWithExponent(val, int32(d.dp)-int32(d.nd))
  294. }
  295. // NewFromFloatWithExponent converts a float64 to Decimal, with an arbitrary
  296. // number of fractional digits.
  297. //
  298. // Example:
  299. //
  300. // NewFromFloatWithExponent(123.456, -2).String() // output: "123.46"
  301. //
  302. func NewFromFloatWithExponent(value float64, exp int32) Decimal {
  303. if math.IsNaN(value) || math.IsInf(value, 0) {
  304. panic(fmt.Sprintf("Cannot create a Decimal from %v", value))
  305. }
  306. bits := math.Float64bits(value)
  307. mant := bits & (1<<52 - 1)
  308. exp2 := int32((bits >> 52) & (1<<11 - 1))
  309. sign := bits >> 63
  310. if exp2 == 0 {
  311. // specials
  312. if mant == 0 {
  313. return Decimal{}
  314. }
  315. // subnormal
  316. exp2++
  317. } else {
  318. // normal
  319. mant |= 1 << 52
  320. }
  321. exp2 -= 1023 + 52
  322. // normalizing base-2 values
  323. for mant&1 == 0 {
  324. mant = mant >> 1
  325. exp2++
  326. }
  327. // maximum number of fractional base-10 digits to represent 2^N exactly cannot be more than -N if N<0
  328. if exp < 0 && exp < exp2 {
  329. if exp2 < 0 {
  330. exp = exp2
  331. } else {
  332. exp = 0
  333. }
  334. }
  335. // representing 10^M * 2^N as 5^M * 2^(M+N)
  336. exp2 -= exp
  337. temp := big.NewInt(1)
  338. dMant := big.NewInt(int64(mant))
  339. // applying 5^M
  340. if exp > 0 {
  341. temp = temp.SetInt64(int64(exp))
  342. temp = temp.Exp(fiveInt, temp, nil)
  343. } else if exp < 0 {
  344. temp = temp.SetInt64(-int64(exp))
  345. temp = temp.Exp(fiveInt, temp, nil)
  346. dMant = dMant.Mul(dMant, temp)
  347. temp = temp.SetUint64(1)
  348. }
  349. // applying 2^(M+N)
  350. if exp2 > 0 {
  351. dMant = dMant.Lsh(dMant, uint(exp2))
  352. } else if exp2 < 0 {
  353. temp = temp.Lsh(temp, uint(-exp2))
  354. }
  355. // rounding and downscaling
  356. if exp > 0 || exp2 < 0 {
  357. halfDown := new(big.Int).Rsh(temp, 1)
  358. dMant = dMant.Add(dMant, halfDown)
  359. dMant = dMant.Quo(dMant, temp)
  360. }
  361. if sign == 1 {
  362. dMant = dMant.Neg(dMant)
  363. }
  364. return Decimal{
  365. value: dMant,
  366. exp: exp,
  367. }
  368. }
  369. // rescale returns a rescaled version of the decimal. Returned
  370. // decimal may be less precise if the given exponent is bigger
  371. // than the initial exponent of the Decimal.
  372. // NOTE: this will truncate, NOT round
  373. //
  374. // Example:
  375. //
  376. // d := New(12345, -4)
  377. // d2 := d.rescale(-1)
  378. // d3 := d2.rescale(-4)
  379. // println(d1)
  380. // println(d2)
  381. // println(d3)
  382. //
  383. // Output:
  384. //
  385. // 1.2345
  386. // 1.2
  387. // 1.2000
  388. //
  389. func (d Decimal) rescale(exp int32) Decimal {
  390. d.ensureInitialized()
  391. if d.exp == exp {
  392. return Decimal{
  393. new(big.Int).Set(d.value),
  394. d.exp,
  395. }
  396. }
  397. // NOTE(vadim): must convert exps to float64 before - to prevent overflow
  398. diff := math.Abs(float64(exp) - float64(d.exp))
  399. value := new(big.Int).Set(d.value)
  400. expScale := new(big.Int).Exp(tenInt, big.NewInt(int64(diff)), nil)
  401. if exp > d.exp {
  402. value = value.Quo(value, expScale)
  403. } else if exp < d.exp {
  404. value = value.Mul(value, expScale)
  405. }
  406. return Decimal{
  407. value: value,
  408. exp: exp,
  409. }
  410. }
  411. // Abs returns the absolute value of the decimal.
  412. func (d Decimal) Abs() Decimal {
  413. d.ensureInitialized()
  414. d2Value := new(big.Int).Abs(d.value)
  415. return Decimal{
  416. value: d2Value,
  417. exp: d.exp,
  418. }
  419. }
  420. // Add returns d + d2.
  421. func (d Decimal) Add(d2 Decimal) Decimal {
  422. rd, rd2 := RescalePair(d, d2)
  423. d3Value := new(big.Int).Add(rd.value, rd2.value)
  424. return Decimal{
  425. value: d3Value,
  426. exp: rd.exp,
  427. }
  428. }
  429. // Sub returns d - d2.
  430. func (d Decimal) Sub(d2 Decimal) Decimal {
  431. rd, rd2 := RescalePair(d, d2)
  432. d3Value := new(big.Int).Sub(rd.value, rd2.value)
  433. return Decimal{
  434. value: d3Value,
  435. exp: rd.exp,
  436. }
  437. }
  438. // Neg returns -d.
  439. func (d Decimal) Neg() Decimal {
  440. d.ensureInitialized()
  441. val := new(big.Int).Neg(d.value)
  442. return Decimal{
  443. value: val,
  444. exp: d.exp,
  445. }
  446. }
  447. // Mul returns d * d2.
  448. func (d Decimal) Mul(d2 Decimal) Decimal {
  449. d.ensureInitialized()
  450. d2.ensureInitialized()
  451. expInt64 := int64(d.exp) + int64(d2.exp)
  452. if expInt64 > math.MaxInt32 || expInt64 < math.MinInt32 {
  453. // NOTE(vadim): better to panic than give incorrect results, as
  454. // Decimals are usually used for money
  455. panic(fmt.Sprintf("exponent %v overflows an int32!", expInt64))
  456. }
  457. d3Value := new(big.Int).Mul(d.value, d2.value)
  458. return Decimal{
  459. value: d3Value,
  460. exp: int32(expInt64),
  461. }
  462. }
  463. // Shift shifts the decimal in base 10.
  464. // It shifts left when shift is positive and right if shift is negative.
  465. // In simpler terms, the given value for shift is added to the exponent
  466. // of the decimal.
  467. func (d Decimal) Shift(shift int32) Decimal {
  468. d.ensureInitialized()
  469. return Decimal{
  470. value: new(big.Int).Set(d.value),
  471. exp: d.exp + shift,
  472. }
  473. }
  474. // Div returns d / d2. If it doesn't divide exactly, the result will have
  475. // DivisionPrecision digits after the decimal point.
  476. func (d Decimal) Div(d2 Decimal) Decimal {
  477. return d.DivRound(d2, int32(DivisionPrecision))
  478. }
  479. // QuoRem does divsion with remainder
  480. // d.QuoRem(d2,precision) returns quotient q and remainder r such that
  481. // d = d2 * q + r, q an integer multiple of 10^(-precision)
  482. // 0 <= r < abs(d2) * 10 ^(-precision) if d>=0
  483. // 0 >= r > -abs(d2) * 10 ^(-precision) if d<0
  484. // Note that precision<0 is allowed as input.
  485. func (d Decimal) QuoRem(d2 Decimal, precision int32) (Decimal, Decimal) {
  486. d.ensureInitialized()
  487. d2.ensureInitialized()
  488. if d2.value.Sign() == 0 {
  489. panic("decimal division by 0")
  490. }
  491. scale := -precision
  492. e := int64(d.exp - d2.exp - scale)
  493. if e > math.MaxInt32 || e < math.MinInt32 {
  494. panic("overflow in decimal QuoRem")
  495. }
  496. var aa, bb, expo big.Int
  497. var scalerest int32
  498. // d = a 10^ea
  499. // d2 = b 10^eb
  500. if e < 0 {
  501. aa = *d.value
  502. expo.SetInt64(-e)
  503. bb.Exp(tenInt, &expo, nil)
  504. bb.Mul(d2.value, &bb)
  505. scalerest = d.exp
  506. // now aa = a
  507. // bb = b 10^(scale + eb - ea)
  508. } else {
  509. expo.SetInt64(e)
  510. aa.Exp(tenInt, &expo, nil)
  511. aa.Mul(d.value, &aa)
  512. bb = *d2.value
  513. scalerest = scale + d2.exp
  514. // now aa = a ^ (ea - eb - scale)
  515. // bb = b
  516. }
  517. var q, r big.Int
  518. q.QuoRem(&aa, &bb, &r)
  519. dq := Decimal{value: &q, exp: scale}
  520. dr := Decimal{value: &r, exp: scalerest}
  521. return dq, dr
  522. }
  523. // DivRound divides and rounds to a given precision
  524. // i.e. to an integer multiple of 10^(-precision)
  525. // for a positive quotient digit 5 is rounded up, away from 0
  526. // if the quotient is negative then digit 5 is rounded down, away from 0
  527. // Note that precision<0 is allowed as input.
  528. func (d Decimal) DivRound(d2 Decimal, precision int32) Decimal {
  529. // QuoRem already checks initialization
  530. q, r := d.QuoRem(d2, precision)
  531. // the actual rounding decision is based on comparing r*10^precision and d2/2
  532. // instead compare 2 r 10 ^precision and d2
  533. var rv2 big.Int
  534. rv2.Abs(r.value)
  535. rv2.Lsh(&rv2, 1)
  536. // now rv2 = abs(r.value) * 2
  537. r2 := Decimal{value: &rv2, exp: r.exp + precision}
  538. // r2 is now 2 * r * 10 ^ precision
  539. var c = r2.Cmp(d2.Abs())
  540. if c < 0 {
  541. return q
  542. }
  543. if d.value.Sign()*d2.value.Sign() < 0 {
  544. return q.Sub(New(1, -precision))
  545. }
  546. return q.Add(New(1, -precision))
  547. }
  548. // Mod returns d % d2.
  549. func (d Decimal) Mod(d2 Decimal) Decimal {
  550. quo := d.Div(d2).Truncate(0)
  551. return d.Sub(d2.Mul(quo))
  552. }
  553. // Pow returns d to the power d2
  554. func (d Decimal) Pow(d2 Decimal) Decimal {
  555. var temp Decimal
  556. if d2.IntPart() == 0 {
  557. return NewFromFloat(1)
  558. }
  559. temp = d.Pow(d2.Div(NewFromFloat(2)))
  560. if d2.IntPart()%2 == 0 {
  561. return temp.Mul(temp)
  562. }
  563. if d2.IntPart() > 0 {
  564. return temp.Mul(temp).Mul(d)
  565. }
  566. return temp.Mul(temp).Div(d)
  567. }
  568. // IsInteger returns true when decimal can be represented as an integer value, otherwise, it returns false.
  569. func (d Decimal) IsInteger() bool {
  570. // The most typical case, all decimal with exponent higher or equal 0 can be represented as integer
  571. if d.exp >= 0 {
  572. return true
  573. }
  574. // When the exponent is negative we have to check every number after the decimal place
  575. // If all of them are zeroes, we are sure that given decimal can be represented as an integer
  576. var r big.Int
  577. q := big.NewInt(0).Set(d.value)
  578. for z := abs(d.exp); z > 0; z-- {
  579. q.QuoRem(q, tenInt, &r)
  580. if r.Cmp(zeroInt) != 0 {
  581. return false
  582. }
  583. }
  584. return true
  585. }
  586. // Abs calculates absolute value of any int32. Used for calculating absolute value of decimal's exponent.
  587. func abs(n int32) int32 {
  588. if n < 0 {
  589. return -n
  590. }
  591. return n
  592. }
  593. // Cmp compares the numbers represented by d and d2 and returns:
  594. //
  595. // -1 if d < d2
  596. // 0 if d == d2
  597. // +1 if d > d2
  598. //
  599. func (d Decimal) Cmp(d2 Decimal) int {
  600. d.ensureInitialized()
  601. d2.ensureInitialized()
  602. if d.exp == d2.exp {
  603. return d.value.Cmp(d2.value)
  604. }
  605. rd, rd2 := RescalePair(d, d2)
  606. return rd.value.Cmp(rd2.value)
  607. }
  608. // Equal returns whether the numbers represented by d and d2 are equal.
  609. func (d Decimal) Equal(d2 Decimal) bool {
  610. return d.Cmp(d2) == 0
  611. }
  612. // Equals is deprecated, please use Equal method instead
  613. func (d Decimal) Equals(d2 Decimal) bool {
  614. return d.Equal(d2)
  615. }
  616. // GreaterThan (GT) returns true when d is greater than d2.
  617. func (d Decimal) GreaterThan(d2 Decimal) bool {
  618. return d.Cmp(d2) == 1
  619. }
  620. // GreaterThanOrEqual (GTE) returns true when d is greater than or equal to d2.
  621. func (d Decimal) GreaterThanOrEqual(d2 Decimal) bool {
  622. cmp := d.Cmp(d2)
  623. return cmp == 1 || cmp == 0
  624. }
  625. // LessThan (LT) returns true when d is less than d2.
  626. func (d Decimal) LessThan(d2 Decimal) bool {
  627. return d.Cmp(d2) == -1
  628. }
  629. // LessThanOrEqual (LTE) returns true when d is less than or equal to d2.
  630. func (d Decimal) LessThanOrEqual(d2 Decimal) bool {
  631. cmp := d.Cmp(d2)
  632. return cmp == -1 || cmp == 0
  633. }
  634. // Sign returns:
  635. //
  636. // -1 if d < 0
  637. // 0 if d == 0
  638. // +1 if d > 0
  639. //
  640. func (d Decimal) Sign() int {
  641. if d.value == nil {
  642. return 0
  643. }
  644. return d.value.Sign()
  645. }
  646. // IsPositive return
  647. //
  648. // true if d > 0
  649. // false if d == 0
  650. // false if d < 0
  651. func (d Decimal) IsPositive() bool {
  652. return d.Sign() == 1
  653. }
  654. // IsNegative return
  655. //
  656. // true if d < 0
  657. // false if d == 0
  658. // false if d > 0
  659. func (d Decimal) IsNegative() bool {
  660. return d.Sign() == -1
  661. }
  662. // IsZero return
  663. //
  664. // true if d == 0
  665. // false if d > 0
  666. // false if d < 0
  667. func (d Decimal) IsZero() bool {
  668. return d.Sign() == 0
  669. }
  670. // Exponent returns the exponent, or scale component of the decimal.
  671. func (d Decimal) Exponent() int32 {
  672. return d.exp
  673. }
  674. // Coefficient returns the coefficient of the decimal. It is scaled by 10^Exponent()
  675. func (d Decimal) Coefficient() *big.Int {
  676. d.ensureInitialized()
  677. // we copy the coefficient so that mutating the result does not mutate the
  678. // Decimal.
  679. return big.NewInt(0).Set(d.value)
  680. }
  681. // IntPart returns the integer component of the decimal.
  682. func (d Decimal) IntPart() int64 {
  683. scaledD := d.rescale(0)
  684. return scaledD.value.Int64()
  685. }
  686. // BigInt returns integer component of the decimal as a BigInt.
  687. func (d Decimal) BigInt() *big.Int {
  688. scaledD := d.rescale(0)
  689. i := &big.Int{}
  690. i.SetString(scaledD.String(), 10)
  691. return i
  692. }
  693. // BigFloat returns decimal as BigFloat.
  694. // Be aware that casting decimal to BigFloat might cause a loss of precision.
  695. func (d Decimal) BigFloat() *big.Float {
  696. f := &big.Float{}
  697. f.SetString(d.String())
  698. return f
  699. }
  700. // Rat returns a rational number representation of the decimal.
  701. func (d Decimal) Rat() *big.Rat {
  702. d.ensureInitialized()
  703. if d.exp <= 0 {
  704. // NOTE(vadim): must negate after casting to prevent int32 overflow
  705. denom := new(big.Int).Exp(tenInt, big.NewInt(-int64(d.exp)), nil)
  706. return new(big.Rat).SetFrac(d.value, denom)
  707. }
  708. mul := new(big.Int).Exp(tenInt, big.NewInt(int64(d.exp)), nil)
  709. num := new(big.Int).Mul(d.value, mul)
  710. return new(big.Rat).SetFrac(num, oneInt)
  711. }
  712. // Float64 returns the nearest float64 value for d and a bool indicating
  713. // whether f represents d exactly.
  714. // For more details, see the documentation for big.Rat.Float64
  715. func (d Decimal) Float64() (f float64, exact bool) {
  716. return d.Rat().Float64()
  717. }
  718. // String returns the string representation of the decimal
  719. // with the fixed point.
  720. //
  721. // Example:
  722. //
  723. // d := New(-12345, -3)
  724. // println(d.String())
  725. //
  726. // Output:
  727. //
  728. // -12.345
  729. //
  730. func (d Decimal) String() string {
  731. return d.string(true)
  732. }
  733. // StringFixed returns a rounded fixed-point string with places digits after
  734. // the decimal point.
  735. //
  736. // Example:
  737. //
  738. // NewFromFloat(0).StringFixed(2) // output: "0.00"
  739. // NewFromFloat(0).StringFixed(0) // output: "0"
  740. // NewFromFloat(5.45).StringFixed(0) // output: "5"
  741. // NewFromFloat(5.45).StringFixed(1) // output: "5.5"
  742. // NewFromFloat(5.45).StringFixed(2) // output: "5.45"
  743. // NewFromFloat(5.45).StringFixed(3) // output: "5.450"
  744. // NewFromFloat(545).StringFixed(-1) // output: "550"
  745. //
  746. func (d Decimal) StringFixed(places int32) string {
  747. rounded := d.Round(places)
  748. return rounded.string(false)
  749. }
  750. // StringFixedBank returns a banker rounded fixed-point string with places digits
  751. // after the decimal point.
  752. //
  753. // Example:
  754. //
  755. // NewFromFloat(0).StringFixedBank(2) // output: "0.00"
  756. // NewFromFloat(0).StringFixedBank(0) // output: "0"
  757. // NewFromFloat(5.45).StringFixedBank(0) // output: "5"
  758. // NewFromFloat(5.45).StringFixedBank(1) // output: "5.4"
  759. // NewFromFloat(5.45).StringFixedBank(2) // output: "5.45"
  760. // NewFromFloat(5.45).StringFixedBank(3) // output: "5.450"
  761. // NewFromFloat(545).StringFixedBank(-1) // output: "540"
  762. //
  763. func (d Decimal) StringFixedBank(places int32) string {
  764. rounded := d.RoundBank(places)
  765. return rounded.string(false)
  766. }
  767. // StringFixedCash returns a Swedish/Cash rounded fixed-point string. For
  768. // more details see the documentation at function RoundCash.
  769. func (d Decimal) StringFixedCash(interval uint8) string {
  770. rounded := d.RoundCash(interval)
  771. return rounded.string(false)
  772. }
  773. // Round rounds the decimal to places decimal places.
  774. // If places < 0, it will round the integer part to the nearest 10^(-places).
  775. //
  776. // Example:
  777. //
  778. // NewFromFloat(5.45).Round(1).String() // output: "5.5"
  779. // NewFromFloat(545).Round(-1).String() // output: "550"
  780. //
  781. func (d Decimal) Round(places int32) Decimal {
  782. // truncate to places + 1
  783. ret := d.rescale(-places - 1)
  784. // add sign(d) * 0.5
  785. if ret.value.Sign() < 0 {
  786. ret.value.Sub(ret.value, fiveInt)
  787. } else {
  788. ret.value.Add(ret.value, fiveInt)
  789. }
  790. // floor for positive numbers, ceil for negative numbers
  791. _, m := ret.value.DivMod(ret.value, tenInt, new(big.Int))
  792. ret.exp++
  793. if ret.value.Sign() < 0 && m.Cmp(zeroInt) != 0 {
  794. ret.value.Add(ret.value, oneInt)
  795. }
  796. return ret
  797. }
  798. // RoundUp rounds the decimal towards +infinity.
  799. //
  800. // Example:
  801. //
  802. // NewFromFloat(545).RoundUp(-2).String() // output: "600"
  803. // NewFromFloat(1.1001).RoundUp(2).String() // output: "1.11"
  804. // NewFromFloat(-1.454).RoundUp(1).String() // output: "-1.4"
  805. //
  806. func (d Decimal) RoundUp(places int32) Decimal {
  807. if d.exp >= -places {
  808. return d
  809. }
  810. rescaled := d.rescale(-places)
  811. if d.value.Sign() > 0 {
  812. rescaled.value.Add(rescaled.value, oneInt)
  813. }
  814. return rescaled
  815. }
  816. // RoundDown rounds the decimal towards -infinity.
  817. //
  818. // Example:
  819. //
  820. // NewFromFloat(545).RoundDown(-2).String() // output: "500"
  821. // NewFromFloat(1.1001).RoundDown(2).String() // output: "1.1"
  822. // NewFromFloat(-1.454).RoundDown(1).String() // output: "-1.5"
  823. //
  824. func (d Decimal) RoundDown(places int32) Decimal {
  825. if d.exp >= -places {
  826. return d
  827. }
  828. rescaled := d.rescale(-places)
  829. if d.value.Sign() < 0 {
  830. rescaled.value.Sub(rescaled.value, oneInt)
  831. }
  832. return rescaled
  833. }
  834. // RoundBank rounds the decimal to places decimal places.
  835. // If the final digit to round is equidistant from the nearest two integers the
  836. // rounded value is taken as the even number
  837. //
  838. // If places < 0, it will round the integer part to the nearest 10^(-places).
  839. //
  840. // Examples:
  841. //
  842. // NewFromFloat(5.45).RoundBank(1).String() // output: "5.4"
  843. // NewFromFloat(545).RoundBank(-1).String() // output: "540"
  844. // NewFromFloat(5.46).RoundBank(1).String() // output: "5.5"
  845. // NewFromFloat(546).RoundBank(-1).String() // output: "550"
  846. // NewFromFloat(5.55).RoundBank(1).String() // output: "5.6"
  847. // NewFromFloat(555).RoundBank(-1).String() // output: "560"
  848. //
  849. func (d Decimal) RoundBank(places int32) Decimal {
  850. round := d.Round(places)
  851. remainder := d.Sub(round).Abs()
  852. half := New(5, -places-1)
  853. if remainder.Cmp(half) == 0 && round.value.Bit(0) != 0 {
  854. if round.value.Sign() < 0 {
  855. round.value.Add(round.value, oneInt)
  856. } else {
  857. round.value.Sub(round.value, oneInt)
  858. }
  859. }
  860. return round
  861. }
  862. // RoundCash aka Cash/Penny/öre rounding rounds decimal to a specific
  863. // interval. The amount payable for a cash transaction is rounded to the nearest
  864. // multiple of the minimum currency unit available. The following intervals are
  865. // available: 5, 10, 25, 50 and 100; any other number throws a panic.
  866. // 5: 5 cent rounding 3.43 => 3.45
  867. // 10: 10 cent rounding 3.45 => 3.50 (5 gets rounded up)
  868. // 25: 25 cent rounding 3.41 => 3.50
  869. // 50: 50 cent rounding 3.75 => 4.00
  870. // 100: 100 cent rounding 3.50 => 4.00
  871. // For more details: https://en.wikipedia.org/wiki/Cash_rounding
  872. func (d Decimal) RoundCash(interval uint8) Decimal {
  873. var iVal *big.Int
  874. switch interval {
  875. case 5:
  876. iVal = twentyInt
  877. case 10:
  878. iVal = tenInt
  879. case 25:
  880. iVal = fourInt
  881. case 50:
  882. iVal = twoInt
  883. case 100:
  884. iVal = oneInt
  885. default:
  886. panic(fmt.Sprintf("Decimal does not support this Cash rounding interval `%d`. Supported: 5, 10, 25, 50, 100", interval))
  887. }
  888. dVal := Decimal{
  889. value: iVal,
  890. }
  891. // TODO: optimize those calculations to reduce the high allocations (~29 allocs).
  892. return d.Mul(dVal).Round(0).Div(dVal).Truncate(2)
  893. }
  894. // Floor returns the nearest integer value less than or equal to d.
  895. func (d Decimal) Floor() Decimal {
  896. d.ensureInitialized()
  897. if d.exp >= 0 {
  898. return d
  899. }
  900. exp := big.NewInt(10)
  901. // NOTE(vadim): must negate after casting to prevent int32 overflow
  902. exp.Exp(exp, big.NewInt(-int64(d.exp)), nil)
  903. z := new(big.Int).Div(d.value, exp)
  904. return Decimal{value: z, exp: 0}
  905. }
  906. // Ceil returns the nearest integer value greater than or equal to d.
  907. func (d Decimal) Ceil() Decimal {
  908. d.ensureInitialized()
  909. if d.exp >= 0 {
  910. return d
  911. }
  912. exp := big.NewInt(10)
  913. // NOTE(vadim): must negate after casting to prevent int32 overflow
  914. exp.Exp(exp, big.NewInt(-int64(d.exp)), nil)
  915. z, m := new(big.Int).DivMod(d.value, exp, new(big.Int))
  916. if m.Cmp(zeroInt) != 0 {
  917. z.Add(z, oneInt)
  918. }
  919. return Decimal{value: z, exp: 0}
  920. }
  921. // Truncate truncates off digits from the number, without rounding.
  922. //
  923. // NOTE: precision is the last digit that will not be truncated (must be >= 0).
  924. //
  925. // Example:
  926. //
  927. // decimal.NewFromString("123.456").Truncate(2).String() // "123.45"
  928. //
  929. func (d Decimal) Truncate(precision int32) Decimal {
  930. d.ensureInitialized()
  931. if precision >= 0 && -precision > d.exp {
  932. return d.rescale(-precision)
  933. }
  934. return d
  935. }
  936. // UnmarshalJSON implements the json.Unmarshaler interface.
  937. func (d *Decimal) UnmarshalJSON(decimalBytes []byte) error {
  938. if string(decimalBytes) == "null" {
  939. return nil
  940. }
  941. str, err := unquoteIfQuoted(decimalBytes)
  942. if err != nil {
  943. return fmt.Errorf("error decoding string '%s': %s", decimalBytes, err)
  944. }
  945. decimal, err := NewFromString(str)
  946. *d = decimal
  947. if err != nil {
  948. return fmt.Errorf("error decoding string '%s': %s", str, err)
  949. }
  950. return nil
  951. }
  952. // MarshalJSON implements the json.Marshaler interface.
  953. func (d Decimal) MarshalJSON() ([]byte, error) {
  954. var str string
  955. if MarshalJSONWithoutQuotes {
  956. str = d.String()
  957. } else {
  958. str = "\"" + d.String() + "\""
  959. }
  960. return []byte(str), nil
  961. }
  962. // UnmarshalBinary implements the encoding.BinaryUnmarshaler interface. As a string representation
  963. // is already used when encoding to text, this method stores that string as []byte
  964. func (d *Decimal) UnmarshalBinary(data []byte) error {
  965. // Extract the exponent
  966. d.exp = int32(binary.BigEndian.Uint32(data[:4]))
  967. // Extract the value
  968. d.value = new(big.Int)
  969. return d.value.GobDecode(data[4:])
  970. }
  971. // MarshalBinary implements the encoding.BinaryMarshaler interface.
  972. func (d Decimal) MarshalBinary() (data []byte, err error) {
  973. // Write the exponent first since it's a fixed size
  974. v1 := make([]byte, 4)
  975. binary.BigEndian.PutUint32(v1, uint32(d.exp))
  976. // Add the value
  977. var v2 []byte
  978. if v2, err = d.value.GobEncode(); err != nil {
  979. return
  980. }
  981. // Return the byte array
  982. data = append(v1, v2...)
  983. return
  984. }
  985. // Scan implements the sql.Scanner interface for database deserialization.
  986. func (d *Decimal) Scan(value interface{}) error {
  987. // first try to see if the data is stored in database as a Numeric datatype
  988. switch v := value.(type) {
  989. case float32:
  990. *d = NewFromFloat(float64(v))
  991. return nil
  992. case float64:
  993. // numeric in sqlite3 sends us float64
  994. *d = NewFromFloat(v)
  995. return nil
  996. case int64:
  997. // at least in sqlite3 when the value is 0 in db, the data is sent
  998. // to us as an int64 instead of a float64 ...
  999. *d = New(v, 0)
  1000. return nil
  1001. default:
  1002. // default is trying to interpret value stored as string
  1003. str, err := unquoteIfQuoted(v)
  1004. if err != nil {
  1005. return err
  1006. }
  1007. *d, err = NewFromString(str)
  1008. return err
  1009. }
  1010. }
  1011. // Value implements the driver.Valuer interface for database serialization.
  1012. func (d Decimal) Value() (driver.Value, error) {
  1013. return d.String(), nil
  1014. }
  1015. // UnmarshalText implements the encoding.TextUnmarshaler interface for XML
  1016. // deserialization.
  1017. func (d *Decimal) UnmarshalText(text []byte) error {
  1018. str := string(text)
  1019. dec, err := NewFromString(str)
  1020. *d = dec
  1021. if err != nil {
  1022. return fmt.Errorf("error decoding string '%s': %s", str, err)
  1023. }
  1024. return nil
  1025. }
  1026. // MarshalText implements the encoding.TextMarshaler interface for XML
  1027. // serialization.
  1028. func (d Decimal) MarshalText() (text []byte, err error) {
  1029. return []byte(d.String()), nil
  1030. }
  1031. // GobEncode implements the gob.GobEncoder interface for gob serialization.
  1032. func (d Decimal) GobEncode() ([]byte, error) {
  1033. return d.MarshalBinary()
  1034. }
  1035. // GobDecode implements the gob.GobDecoder interface for gob serialization.
  1036. func (d *Decimal) GobDecode(data []byte) error {
  1037. return d.UnmarshalBinary(data)
  1038. }
  1039. // StringScaled first scales the decimal then calls .String() on it.
  1040. // NOTE: buggy, unintuitive, and DEPRECATED! Use StringFixed instead.
  1041. func (d Decimal) StringScaled(exp int32) string {
  1042. return d.rescale(exp).String()
  1043. }
  1044. func (d Decimal) string(trimTrailingZeros bool) string {
  1045. if d.exp >= 0 {
  1046. return d.rescale(0).value.String()
  1047. }
  1048. abs := new(big.Int).Abs(d.value)
  1049. str := abs.String()
  1050. var intPart, fractionalPart string
  1051. // NOTE(vadim): this cast to int will cause bugs if d.exp == INT_MIN
  1052. // and you are on a 32-bit machine. Won't fix this super-edge case.
  1053. dExpInt := int(d.exp)
  1054. if len(str) > -dExpInt {
  1055. intPart = str[:len(str)+dExpInt]
  1056. fractionalPart = str[len(str)+dExpInt:]
  1057. } else {
  1058. intPart = "0"
  1059. num0s := -dExpInt - len(str)
  1060. fractionalPart = strings.Repeat("0", num0s) + str
  1061. }
  1062. if trimTrailingZeros {
  1063. i := len(fractionalPart) - 1
  1064. for ; i >= 0; i-- {
  1065. if fractionalPart[i] != '0' {
  1066. break
  1067. }
  1068. }
  1069. fractionalPart = fractionalPart[:i+1]
  1070. }
  1071. number := intPart
  1072. if len(fractionalPart) > 0 {
  1073. number += "." + fractionalPart
  1074. }
  1075. if d.value.Sign() < 0 {
  1076. return "-" + number
  1077. }
  1078. return number
  1079. }
  1080. func (d *Decimal) ensureInitialized() {
  1081. if d.value == nil {
  1082. d.value = new(big.Int)
  1083. }
  1084. }
  1085. // Min returns the smallest Decimal that was passed in the arguments.
  1086. //
  1087. // To call this function with an array, you must do:
  1088. //
  1089. // Min(arr[0], arr[1:]...)
  1090. //
  1091. // This makes it harder to accidentally call Min with 0 arguments.
  1092. func Min(first Decimal, rest ...Decimal) Decimal {
  1093. ans := first
  1094. for _, item := range rest {
  1095. if item.Cmp(ans) < 0 {
  1096. ans = item
  1097. }
  1098. }
  1099. return ans
  1100. }
  1101. // Max returns the largest Decimal that was passed in the arguments.
  1102. //
  1103. // To call this function with an array, you must do:
  1104. //
  1105. // Max(arr[0], arr[1:]...)
  1106. //
  1107. // This makes it harder to accidentally call Max with 0 arguments.
  1108. func Max(first Decimal, rest ...Decimal) Decimal {
  1109. ans := first
  1110. for _, item := range rest {
  1111. if item.Cmp(ans) > 0 {
  1112. ans = item
  1113. }
  1114. }
  1115. return ans
  1116. }
  1117. // Sum returns the combined total of the provided first and rest Decimals
  1118. func Sum(first Decimal, rest ...Decimal) Decimal {
  1119. total := first
  1120. for _, item := range rest {
  1121. total = total.Add(item)
  1122. }
  1123. return total
  1124. }
  1125. // Avg returns the average value of the provided first and rest Decimals
  1126. func Avg(first Decimal, rest ...Decimal) Decimal {
  1127. count := New(int64(len(rest)+1), 0)
  1128. sum := Sum(first, rest...)
  1129. return sum.Div(count)
  1130. }
  1131. // RescalePair rescales two decimals to common exponential value (minimal exp of both decimals)
  1132. func RescalePair(d1 Decimal, d2 Decimal) (Decimal, Decimal) {
  1133. d1.ensureInitialized()
  1134. d2.ensureInitialized()
  1135. if d1.exp == d2.exp {
  1136. return d1, d2
  1137. }
  1138. baseScale := min(d1.exp, d2.exp)
  1139. if baseScale != d1.exp {
  1140. return d1.rescale(baseScale), d2
  1141. }
  1142. return d1, d2.rescale(baseScale)
  1143. }
  1144. func min(x, y int32) int32 {
  1145. if x >= y {
  1146. return y
  1147. }
  1148. return x
  1149. }
  1150. func unquoteIfQuoted(value interface{}) (string, error) {
  1151. var bytes []byte
  1152. switch v := value.(type) {
  1153. case string:
  1154. bytes = []byte(v)
  1155. case []byte:
  1156. bytes = v
  1157. default:
  1158. return "", fmt.Errorf("could not convert value '%+v' to byte array of type '%T'",
  1159. value, value)
  1160. }
  1161. // If the amount is quoted, strip the quotes
  1162. if len(bytes) > 2 && bytes[0] == '"' && bytes[len(bytes)-1] == '"' {
  1163. bytes = bytes[1 : len(bytes)-1]
  1164. }
  1165. return string(bytes), nil
  1166. }
  1167. // NullDecimal represents a nullable decimal with compatibility for
  1168. // scanning null values from the database.
  1169. type NullDecimal struct {
  1170. Decimal Decimal
  1171. Valid bool
  1172. }
  1173. // Scan implements the sql.Scanner interface for database deserialization.
  1174. func (d *NullDecimal) Scan(value interface{}) error {
  1175. if value == nil {
  1176. d.Valid = false
  1177. return nil
  1178. }
  1179. d.Valid = true
  1180. return d.Decimal.Scan(value)
  1181. }
  1182. // Value implements the driver.Valuer interface for database serialization.
  1183. func (d NullDecimal) Value() (driver.Value, error) {
  1184. if !d.Valid {
  1185. return nil, nil
  1186. }
  1187. return d.Decimal.Value()
  1188. }
  1189. // UnmarshalJSON implements the json.Unmarshaler interface.
  1190. func (d *NullDecimal) UnmarshalJSON(decimalBytes []byte) error {
  1191. if string(decimalBytes) == "null" {
  1192. d.Valid = false
  1193. return nil
  1194. }
  1195. d.Valid = true
  1196. return d.Decimal.UnmarshalJSON(decimalBytes)
  1197. }
  1198. // MarshalJSON implements the json.Marshaler interface.
  1199. func (d NullDecimal) MarshalJSON() ([]byte, error) {
  1200. if !d.Valid {
  1201. return []byte("null"), nil
  1202. }
  1203. return d.Decimal.MarshalJSON()
  1204. }
  1205. // Trig functions
  1206. // Atan returns the arctangent, in radians, of x.
  1207. func (d Decimal) Atan() Decimal {
  1208. if d.Equal(NewFromFloat(0.0)) {
  1209. return d
  1210. }
  1211. if d.GreaterThan(NewFromFloat(0.0)) {
  1212. return d.satan()
  1213. }
  1214. return d.Neg().satan().Neg()
  1215. }
  1216. func (d Decimal) xatan() Decimal {
  1217. P0 := NewFromFloat(-8.750608600031904122785e-01)
  1218. P1 := NewFromFloat(-1.615753718733365076637e+01)
  1219. P2 := NewFromFloat(-7.500855792314704667340e+01)
  1220. P3 := NewFromFloat(-1.228866684490136173410e+02)
  1221. P4 := NewFromFloat(-6.485021904942025371773e+01)
  1222. Q0 := NewFromFloat(2.485846490142306297962e+01)
  1223. Q1 := NewFromFloat(1.650270098316988542046e+02)
  1224. Q2 := NewFromFloat(4.328810604912902668951e+02)
  1225. Q3 := NewFromFloat(4.853903996359136964868e+02)
  1226. Q4 := NewFromFloat(1.945506571482613964425e+02)
  1227. z := d.Mul(d)
  1228. b1 := P0.Mul(z).Add(P1).Mul(z).Add(P2).Mul(z).Add(P3).Mul(z).Add(P4).Mul(z)
  1229. b2 := z.Add(Q0).Mul(z).Add(Q1).Mul(z).Add(Q2).Mul(z).Add(Q3).Mul(z).Add(Q4)
  1230. z = b1.Div(b2)
  1231. z = d.Mul(z).Add(d)
  1232. return z
  1233. }
  1234. // satan reduces its argument (known to be positive)
  1235. // to the range [0, 0.66] and calls xatan.
  1236. func (d Decimal) satan() Decimal {
  1237. Morebits := NewFromFloat(6.123233995736765886130e-17) // pi/2 = PIO2 + Morebits
  1238. Tan3pio8 := NewFromFloat(2.41421356237309504880) // tan(3*pi/8)
  1239. pi := NewFromFloat(3.14159265358979323846264338327950288419716939937510582097494459)
  1240. if d.LessThanOrEqual(NewFromFloat(0.66)) {
  1241. return d.xatan()
  1242. }
  1243. if d.GreaterThan(Tan3pio8) {
  1244. return pi.Div(NewFromFloat(2.0)).Sub(NewFromFloat(1.0).Div(d).xatan()).Add(Morebits)
  1245. }
  1246. return pi.Div(NewFromFloat(4.0)).Add((d.Sub(NewFromFloat(1.0)).Div(d.Add(NewFromFloat(1.0)))).xatan()).Add(NewFromFloat(0.5).Mul(Morebits))
  1247. }
  1248. // sin coefficients
  1249. var _sin = [...]Decimal{
  1250. NewFromFloat(1.58962301576546568060e-10), // 0x3de5d8fd1fd19ccd
  1251. NewFromFloat(-2.50507477628578072866e-8), // 0xbe5ae5e5a9291f5d
  1252. NewFromFloat(2.75573136213857245213e-6), // 0x3ec71de3567d48a1
  1253. NewFromFloat(-1.98412698295895385996e-4), // 0xbf2a01a019bfdf03
  1254. NewFromFloat(8.33333333332211858878e-3), // 0x3f8111111110f7d0
  1255. NewFromFloat(-1.66666666666666307295e-1), // 0xbfc5555555555548
  1256. }
  1257. // Sin returns the sine of the radian argument x.
  1258. func (d Decimal) Sin() Decimal {
  1259. PI4A := NewFromFloat(7.85398125648498535156e-1) // 0x3fe921fb40000000, Pi/4 split into three parts
  1260. PI4B := NewFromFloat(3.77489470793079817668e-8) // 0x3e64442d00000000,
  1261. PI4C := NewFromFloat(2.69515142907905952645e-15) // 0x3ce8469898cc5170,
  1262. M4PI := NewFromFloat(1.273239544735162542821171882678754627704620361328125) // 4/pi
  1263. if d.Equal(NewFromFloat(0.0)) {
  1264. return d
  1265. }
  1266. // make argument positive but save the sign
  1267. sign := false
  1268. if d.LessThan(NewFromFloat(0.0)) {
  1269. d = d.Neg()
  1270. sign = true
  1271. }
  1272. j := d.Mul(M4PI).IntPart() // integer part of x/(Pi/4), as integer for tests on the phase angle
  1273. y := NewFromFloat(float64(j)) // integer part of x/(Pi/4), as float
  1274. // map zeros to origin
  1275. if j&1 == 1 {
  1276. j++
  1277. y = y.Add(NewFromFloat(1.0))
  1278. }
  1279. j &= 7 // octant modulo 2Pi radians (360 degrees)
  1280. // reflect in x axis
  1281. if j > 3 {
  1282. sign = !sign
  1283. j -= 4
  1284. }
  1285. z := d.Sub(y.Mul(PI4A)).Sub(y.Mul(PI4B)).Sub(y.Mul(PI4C)) // Extended precision modular arithmetic
  1286. zz := z.Mul(z)
  1287. if j == 1 || j == 2 {
  1288. w := zz.Mul(zz).Mul(_cos[0].Mul(zz).Add(_cos[1]).Mul(zz).Add(_cos[2]).Mul(zz).Add(_cos[3]).Mul(zz).Add(_cos[4]).Mul(zz).Add(_cos[5]))
  1289. y = NewFromFloat(1.0).Sub(NewFromFloat(0.5).Mul(zz)).Add(w)
  1290. } else {
  1291. y = z.Add(z.Mul(zz).Mul(_sin[0].Mul(zz).Add(_sin[1]).Mul(zz).Add(_sin[2]).Mul(zz).Add(_sin[3]).Mul(zz).Add(_sin[4]).Mul(zz).Add(_sin[5])))
  1292. }
  1293. if sign {
  1294. y = y.Neg()
  1295. }
  1296. return y
  1297. }
  1298. // cos coefficients
  1299. var _cos = [...]Decimal{
  1300. NewFromFloat(-1.13585365213876817300e-11), // 0xbda8fa49a0861a9b
  1301. NewFromFloat(2.08757008419747316778e-9), // 0x3e21ee9d7b4e3f05
  1302. NewFromFloat(-2.75573141792967388112e-7), // 0xbe927e4f7eac4bc6
  1303. NewFromFloat(2.48015872888517045348e-5), // 0x3efa01a019c844f5
  1304. NewFromFloat(-1.38888888888730564116e-3), // 0xbf56c16c16c14f91
  1305. NewFromFloat(4.16666666666665929218e-2), // 0x3fa555555555554b
  1306. }
  1307. // Cos returns the cosine of the radian argument x.
  1308. func (d Decimal) Cos() Decimal {
  1309. PI4A := NewFromFloat(7.85398125648498535156e-1) // 0x3fe921fb40000000, Pi/4 split into three parts
  1310. PI4B := NewFromFloat(3.77489470793079817668e-8) // 0x3e64442d00000000,
  1311. PI4C := NewFromFloat(2.69515142907905952645e-15) // 0x3ce8469898cc5170,
  1312. M4PI := NewFromFloat(1.273239544735162542821171882678754627704620361328125) // 4/pi
  1313. // make argument positive
  1314. sign := false
  1315. if d.LessThan(NewFromFloat(0.0)) {
  1316. d = d.Neg()
  1317. }
  1318. j := d.Mul(M4PI).IntPart() // integer part of x/(Pi/4), as integer for tests on the phase angle
  1319. y := NewFromFloat(float64(j)) // integer part of x/(Pi/4), as float
  1320. // map zeros to origin
  1321. if j&1 == 1 {
  1322. j++
  1323. y = y.Add(NewFromFloat(1.0))
  1324. }
  1325. j &= 7 // octant modulo 2Pi radians (360 degrees)
  1326. // reflect in x axis
  1327. if j > 3 {
  1328. sign = !sign
  1329. j -= 4
  1330. }
  1331. if j > 1 {
  1332. sign = !sign
  1333. }
  1334. z := d.Sub(y.Mul(PI4A)).Sub(y.Mul(PI4B)).Sub(y.Mul(PI4C)) // Extended precision modular arithmetic
  1335. zz := z.Mul(z)
  1336. if j == 1 || j == 2 {
  1337. y = z.Add(z.Mul(zz).Mul(_sin[0].Mul(zz).Add(_sin[1]).Mul(zz).Add(_sin[2]).Mul(zz).Add(_sin[3]).Mul(zz).Add(_sin[4]).Mul(zz).Add(_sin[5])))
  1338. } else {
  1339. w := zz.Mul(zz).Mul(_cos[0].Mul(zz).Add(_cos[1]).Mul(zz).Add(_cos[2]).Mul(zz).Add(_cos[3]).Mul(zz).Add(_cos[4]).Mul(zz).Add(_cos[5]))
  1340. y = NewFromFloat(1.0).Sub(NewFromFloat(0.5).Mul(zz)).Add(w)
  1341. }
  1342. if sign {
  1343. y = y.Neg()
  1344. }
  1345. return y
  1346. }
  1347. var _tanP = [...]Decimal{
  1348. NewFromFloat(-1.30936939181383777646e+4), // 0xc0c992d8d24f3f38
  1349. NewFromFloat(1.15351664838587416140e+6), // 0x413199eca5fc9ddd
  1350. NewFromFloat(-1.79565251976484877988e+7), // 0xc1711fead3299176
  1351. }
  1352. var _tanQ = [...]Decimal{
  1353. NewFromFloat(1.00000000000000000000e+0),
  1354. NewFromFloat(1.36812963470692954678e+4), //0x40cab8a5eeb36572
  1355. NewFromFloat(-1.32089234440210967447e+6), //0xc13427bc582abc96
  1356. NewFromFloat(2.50083801823357915839e+7), //0x4177d98fc2ead8ef
  1357. NewFromFloat(-5.38695755929454629881e+7), //0xc189afe03cbe5a31
  1358. }
  1359. // Tan returns the tangent of the radian argument x.
  1360. func (d Decimal) Tan() Decimal {
  1361. PI4A := NewFromFloat(7.85398125648498535156e-1) // 0x3fe921fb40000000, Pi/4 split into three parts
  1362. PI4B := NewFromFloat(3.77489470793079817668e-8) // 0x3e64442d00000000,
  1363. PI4C := NewFromFloat(2.69515142907905952645e-15) // 0x3ce8469898cc5170,
  1364. M4PI := NewFromFloat(1.273239544735162542821171882678754627704620361328125) // 4/pi
  1365. if d.Equal(NewFromFloat(0.0)) {
  1366. return d
  1367. }
  1368. // make argument positive but save the sign
  1369. sign := false
  1370. if d.LessThan(NewFromFloat(0.0)) {
  1371. d = d.Neg()
  1372. sign = true
  1373. }
  1374. j := d.Mul(M4PI).IntPart() // integer part of x/(Pi/4), as integer for tests on the phase angle
  1375. y := NewFromFloat(float64(j)) // integer part of x/(Pi/4), as float
  1376. // map zeros to origin
  1377. if j&1 == 1 {
  1378. j++
  1379. y = y.Add(NewFromFloat(1.0))
  1380. }
  1381. z := d.Sub(y.Mul(PI4A)).Sub(y.Mul(PI4B)).Sub(y.Mul(PI4C)) // Extended precision modular arithmetic
  1382. zz := z.Mul(z)
  1383. if zz.GreaterThan(NewFromFloat(1e-14)) {
  1384. w := zz.Mul(_tanP[0].Mul(zz).Add(_tanP[1]).Mul(zz).Add(_tanP[2]))
  1385. x := zz.Add(_tanQ[1]).Mul(zz).Add(_tanQ[2]).Mul(zz).Add(_tanQ[3]).Mul(zz).Add(_tanQ[4])
  1386. y = z.Add(z.Mul(w.Div(x)))
  1387. } else {
  1388. y = z
  1389. }
  1390. if j&2 == 2 {
  1391. y = NewFromFloat(-1.0).Div(y)
  1392. }
  1393. if sign {
  1394. y = y.Neg()
  1395. }
  1396. return y
  1397. }