dec.go 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862
  1. // Package dec implements multi-precision decimal arithmetic.
  2. // It supports the numeric type Dec for signed decimals.
  3. // It is based on and complements the multi-precision integer implementation
  4. // (Int) in the Go library (math/big).
  5. //
  6. // Methods are typically of the form:
  7. //
  8. // func (z *Dec) Op(x, y *Dec) *Dec
  9. //
  10. // and implement operations z = x Op y with the result as receiver; if it
  11. // is one of the operands it may be overwritten (and its memory reused).
  12. // To enable chaining of operations, the result is also returned. Methods
  13. // returning a result other than *Dec take one of the operands as the receiver.
  14. //
  15. // Quotient (division) operation uses Scalers and Rounders to specify the
  16. // desired behavior. See Quo, Scaler, and Rounder for details.
  17. //
  18. package dec
  19. // This file implements signed multi-precision decimals.
  20. import (
  21. "fmt"
  22. "io"
  23. "math/big"
  24. "strings"
  25. )
  26. // A Dec represents a signed multi-precision decimal.
  27. // It is stored as a combination of a multi-precision big.Int unscaled value
  28. // and a fixed-precision scale of type Scale.
  29. //
  30. // The mathematical value of a Dec equals:
  31. //
  32. // unscaled * 10**(-scale)
  33. //
  34. // Note that different Dec representations may have equal mathematical values.
  35. //
  36. // unscaled scale String()
  37. // -------------------------
  38. // 0 0 "0"
  39. // 0 2 "0.00"
  40. // 0 -2 "0"
  41. // 1 0 "1"
  42. // 100 2 "1.00"
  43. // 10 0 "10"
  44. // 1 -1 "10"
  45. //
  46. // The zero value for a Dec represents the value 0 with scale 0.
  47. //
  48. type Dec struct {
  49. unscaled big.Int
  50. scale Scale
  51. }
  52. // Scale represents the type used for the scale of a Dec.
  53. type Scale int32
  54. const scaleSize = 4 // bytes in a Scale value
  55. // Scaler represents a method for obtaining the scale to use for the result of
  56. // an operation on x and y.
  57. type Scaler interface {
  58. Scale(x *Dec, y *Dec) Scale
  59. }
  60. // Scale() for a Scale value always returns the Scale value. This allows a Scale
  61. // value to be used as a Scaler when the desired scale is independent of the
  62. // values x and y.
  63. func (s Scale) Scale(x *Dec, y *Dec) Scale {
  64. return s
  65. }
  66. // Rounder represents a method for rounding the (possibly infinite decimal)
  67. // result of a division to a finite Dec. It is used by Dec.Round() and
  68. // Dec.Quo().
  69. //
  70. type Rounder interface {
  71. // When UseRemainder() returns true, the Round() method is passed the
  72. // remainder of the division, expressed as the numerator and denominator of
  73. // a rational.
  74. UseRemainder() bool
  75. // Round sets the rounded value of a quotient to z, and returns z.
  76. // quo is rounded down (truncated towards zero) to the scale obtained from
  77. // the Scaler in Quo().
  78. //
  79. // When the remainder is not used, remNum and remDen are nil.
  80. // When used, the remainder is normalized between -1 and 1; that is:
  81. //
  82. // -|remDen| < remNum < |remDen|
  83. //
  84. // remDen has the same sign as y, and remNum is zero or has the same sign
  85. // as x.
  86. Round(z, quo *Dec, remNum, remDen *big.Int) *Dec
  87. }
  88. var bigInt = [...]*big.Int{
  89. big.NewInt(0), big.NewInt(1), big.NewInt(2), big.NewInt(3), big.NewInt(4),
  90. big.NewInt(5), big.NewInt(6), big.NewInt(7), big.NewInt(8), big.NewInt(9),
  91. big.NewInt(10),
  92. }
  93. var exp10cache [64]big.Int = func() [64]big.Int {
  94. e10, e10i := [64]big.Int{}, bigInt[1]
  95. for i, _ := range e10 {
  96. e10[i].Set(e10i)
  97. e10i = new(big.Int).Mul(e10i, bigInt[10])
  98. }
  99. return e10
  100. }()
  101. // NewDec allocates and returns a new Dec set to the given unscaled value and
  102. // scale.
  103. func NewDec(unscaled *big.Int, scale Scale) *Dec {
  104. return new(Dec).SetUnscaled(unscaled).SetScale(scale)
  105. }
  106. // NewDecInt64 allocates and returns a new Dec set to the given int64 value with
  107. // scale 0.
  108. func NewDecInt64(x int64) *Dec {
  109. return new(Dec).SetUnscaled(big.NewInt(x))
  110. }
  111. // Scale returns the scale of x.
  112. func (x *Dec) Scale() Scale {
  113. return x.scale
  114. }
  115. // Unscaled returns the unscaled value of x.
  116. func (x *Dec) Unscaled() *big.Int {
  117. return &x.unscaled
  118. }
  119. // SetScale sets the scale of x, with the unscaled value unchanged.
  120. // The mathematical value of the Dec changes as if it was multiplied by
  121. // 10**(oldscale-scale).
  122. func (x *Dec) SetScale(scale Scale) *Dec {
  123. x.scale = scale
  124. return x
  125. }
  126. // SetScale sets the unscaled value of x, with the scale unchanged.
  127. func (x *Dec) SetUnscaled(unscaled *big.Int) *Dec {
  128. x.unscaled.Set(unscaled)
  129. return x
  130. }
  131. // Set sets z to the value of x and returns z.
  132. // It does nothing if z == x.
  133. func (z *Dec) Set(x *Dec) *Dec {
  134. if z != x {
  135. z.SetUnscaled(x.Unscaled())
  136. z.SetScale(x.Scale())
  137. }
  138. return z
  139. }
  140. // Move sets z to the value of x, and sets x to zero, unless z == x.
  141. // It is intended for fast assignment from temporary variables without copying
  142. // the underlying array.
  143. func (z *Dec) move(x *Dec) *Dec {
  144. if z != x {
  145. *z = *x
  146. *x = Dec{}
  147. }
  148. return z
  149. }
  150. // Sign returns:
  151. //
  152. // -1 if x < 0
  153. // 0 if x == 0
  154. // +1 if x > 0
  155. //
  156. func (x *Dec) Sign() int {
  157. return x.Unscaled().Sign()
  158. }
  159. // Neg sets z to -x and returns z.
  160. func (z *Dec) Neg(x *Dec) *Dec {
  161. z.SetScale(x.Scale())
  162. z.Unscaled().Neg(x.Unscaled())
  163. return z
  164. }
  165. // Cmp compares x and y and returns:
  166. //
  167. // -1 if x < y
  168. // 0 if x == y
  169. // +1 if x > y
  170. //
  171. func (x *Dec) Cmp(y *Dec) int {
  172. xx, yy := upscale(x, y)
  173. return xx.Unscaled().Cmp(yy.Unscaled())
  174. }
  175. // Abs sets z to |x| (the absolute value of x) and returns z.
  176. func (z *Dec) Abs(x *Dec) *Dec {
  177. z.SetScale(x.Scale())
  178. z.Unscaled().Abs(x.Unscaled())
  179. return z
  180. }
  181. // Add sets z to the sum x+y and returns z.
  182. // The scale of z is the greater of the scales of x and y.
  183. func (z *Dec) Add(x, y *Dec) *Dec {
  184. xx, yy := upscale(x, y)
  185. z.SetScale(xx.Scale())
  186. z.Unscaled().Add(xx.Unscaled(), yy.Unscaled())
  187. return z
  188. }
  189. // Sub sets z to the difference x-y and returns z.
  190. // The scale of z is the greater of the scales of x and y.
  191. func (z *Dec) Sub(x, y *Dec) *Dec {
  192. xx, yy := upscale(x, y)
  193. z.SetScale(xx.Scale())
  194. z.Unscaled().Sub(xx.Unscaled(), yy.Unscaled())
  195. return z
  196. }
  197. // Mul sets z to the product x*y and returns z.
  198. // The scale of z is the sum of the scales of x and y.
  199. func (z *Dec) Mul(x, y *Dec) *Dec {
  200. z.SetScale(x.Scale() + y.Scale())
  201. z.Unscaled().Mul(x.Unscaled(), y.Unscaled())
  202. return z
  203. }
  204. // Round sets z to the value of x rounded to Scale s using Rounder r, and
  205. // returns z.
  206. func (z *Dec) Round(x *Dec, s Scale, r Rounder) *Dec {
  207. return z.Quo(x, NewDecInt64(1), s, r)
  208. }
  209. // Quo sets z to the quotient x/y, with the scale obtained from the given
  210. // Scaler, rounded using the given Rounder.
  211. // If the result from the rounder is nil, Quo also returns nil, and the value
  212. // of z is undefined.
  213. //
  214. // There is no corresponding Div method; the equivalent can be achieved through
  215. // the choice of Rounder used.
  216. //
  217. // See Rounder for details on the various ways for rounding.
  218. func (z *Dec) Quo(x, y *Dec, scaler Scaler, rounder Rounder) *Dec {
  219. s := scaler.Scale(x, y)
  220. var zzz *Dec
  221. if rounder.UseRemainder() {
  222. zz, rA, rB := new(Dec).quoRem(x, y, s, true, new(big.Int), new(big.Int))
  223. zzz = rounder.Round(new(Dec), zz, rA, rB)
  224. } else {
  225. zz, _, _ := new(Dec).quoRem(x, y, s, false, nil, nil)
  226. zzz = rounder.Round(new(Dec), zz, nil, nil)
  227. }
  228. if zzz == nil {
  229. return nil
  230. }
  231. return z.move(zzz)
  232. }
  233. // QuoExact(x, y) is a shorthand for Quo(x, y, ScaleQuoExact, RoundExact).
  234. // If x/y can be expressed as a Dec without rounding, QuoExact sets z to the
  235. // quotient x/y and returns z. Otherwise, it returns nil and the value of z is
  236. // undefined.
  237. func (z *Dec) QuoExact(x, y *Dec) *Dec {
  238. return z.Quo(x, y, ScaleQuoExact, RoundExact)
  239. }
  240. // quoRem sets z to the quotient x/y with the scale s, and if useRem is true,
  241. // it sets remNum and remDen to the numerator and denominator of the remainder.
  242. // It returns z, remNum and remDen.
  243. //
  244. // The remainder is normalized to the range -1 < r < 1 to simplify rounding;
  245. // that is, the results satisfy the following equation:
  246. //
  247. // x / y = z + (remNum/remDen) * 10**(-z.Scale())
  248. //
  249. // See Rounder for more details about rounding.
  250. //
  251. func (z *Dec) quoRem(x, y *Dec, s Scale, useRem bool,
  252. remNum, remDen *big.Int) (*Dec, *big.Int, *big.Int) {
  253. // difference (required adjustment) compared to "canonical" result scale
  254. shift := s - (x.Scale() - y.Scale())
  255. // pointers to adjusted unscaled dividend and divisor
  256. var ix, iy *big.Int
  257. switch {
  258. case shift > 0:
  259. // increased scale: decimal-shift dividend left
  260. ix = new(big.Int).Mul(x.Unscaled(), exp10(shift))
  261. iy = y.Unscaled()
  262. case shift < 0:
  263. // decreased scale: decimal-shift divisor left
  264. ix = x.Unscaled()
  265. iy = new(big.Int).Mul(y.Unscaled(), exp10(-shift))
  266. default:
  267. ix = x.Unscaled()
  268. iy = y.Unscaled()
  269. }
  270. // save a copy of iy in case it to be overwritten with the result
  271. iy2 := iy
  272. if iy == z.Unscaled() {
  273. iy2 = new(big.Int).Set(iy)
  274. }
  275. // set scale
  276. z.SetScale(s)
  277. // set unscaled
  278. if useRem {
  279. // Int division
  280. _, intr := z.Unscaled().QuoRem(ix, iy, new(big.Int))
  281. // set remainder
  282. remNum.Set(intr)
  283. remDen.Set(iy2)
  284. } else {
  285. z.Unscaled().Quo(ix, iy)
  286. }
  287. return z, remNum, remDen
  288. }
  289. // ScaleQuoExact is the Scaler used by QuoExact. It returns a scale that is
  290. // greater than or equal to "x.Scale() - y.Scale()"; it is calculated so that
  291. // the remainder will be zero whenever x/y is a finite decimal.
  292. var ScaleQuoExact Scaler = scaleQuoExact{}
  293. type scaleQuoExact struct{}
  294. func (sqe scaleQuoExact) Scale(x, y *Dec) Scale {
  295. rem := new(big.Rat).SetFrac(x.Unscaled(), y.Unscaled())
  296. f2, f5 := factor2(rem.Denom()), factor(rem.Denom(), bigInt[5])
  297. var f10 Scale
  298. if f2 > f5 {
  299. f10 = Scale(f2)
  300. } else {
  301. f10 = Scale(f5)
  302. }
  303. return x.Scale() - y.Scale() + f10
  304. }
  305. func factor(n *big.Int, p *big.Int) int {
  306. // could be improved for large factors
  307. d, f := n, 0
  308. for {
  309. dd, dm := new(big.Int).DivMod(d, p, new(big.Int))
  310. if dm.Sign() == 0 {
  311. f++
  312. d = dd
  313. } else {
  314. break
  315. }
  316. }
  317. return f
  318. }
  319. func factor2(n *big.Int) int {
  320. // could be improved for large factors
  321. f := 0
  322. for ; n.Bit(f) == 0; f++ {
  323. }
  324. return f
  325. }
  326. type rounder struct {
  327. useRem bool
  328. round func(z, quo *Dec, remNum, remDen *big.Int) *Dec
  329. }
  330. func (r rounder) UseRemainder() bool {
  331. return r.useRem
  332. }
  333. func (r rounder) Round(z, quo *Dec, remNum, remDen *big.Int) *Dec {
  334. return r.round(z, quo, remNum, remDen)
  335. }
  336. // RoundExact returns quo if rem is zero, or nil otherwise. It is intended to
  337. // be used with ScaleQuoExact when it is guaranteed that the result can be
  338. // obtained without rounding. QuoExact is a shorthand for such a quotient
  339. // operation.
  340. //
  341. var RoundExact Rounder = roundExact
  342. // RoundDown rounds towards 0; that is, returns the Dec with the greatest
  343. // absolute value not exceeding that of the result represented by quo and rem.
  344. //
  345. // The following table shows examples of the results for
  346. // Quo(x, y, Scale(scale), RoundDown).
  347. //
  348. // x y scale result
  349. // ------------------------------
  350. // -1.8 10 1 -0.1
  351. // -1.5 10 1 -0.1
  352. // -1.2 10 1 -0.1
  353. // -1.0 10 1 -0.1
  354. // -0.8 10 1 -0.0
  355. // -0.5 10 1 -0.0
  356. // -0.2 10 1 -0.0
  357. // 0.0 10 1 0.0
  358. // 0.2 10 1 0.0
  359. // 0.5 10 1 0.0
  360. // 0.8 10 1 0.0
  361. // 1.0 10 1 0.1
  362. // 1.2 10 1 0.1
  363. // 1.5 10 1 0.1
  364. // 1.8 10 1 0.1
  365. //
  366. var RoundDown Rounder = roundDown
  367. // RoundUp rounds away from 0; that is, returns the Dec with the smallest
  368. // absolute value not smaller than that of the result represented by quo and
  369. // rem.
  370. //
  371. // The following table shows examples of the results for
  372. // Quo(x, y, Scale(scale), RoundUp).
  373. //
  374. // x y scale result
  375. // ------------------------------
  376. // -1.8 10 1 -0.2
  377. // -1.5 10 1 -0.2
  378. // -1.2 10 1 -0.2
  379. // -1.0 10 1 -0.1
  380. // -0.8 10 1 -0.1
  381. // -0.5 10 1 -0.1
  382. // -0.2 10 1 -0.1
  383. // 0.0 10 1 0.0
  384. // 0.2 10 1 0.1
  385. // 0.5 10 1 0.1
  386. // 0.8 10 1 0.1
  387. // 1.0 10 1 0.1
  388. // 1.2 10 1 0.2
  389. // 1.5 10 1 0.2
  390. // 1.8 10 1 0.2
  391. //
  392. var RoundUp Rounder = roundUp
  393. // RoundHalfDown rounds to the nearest Dec, and when the remainder is 1/2, it
  394. // rounds to the Dec with the lower absolute value.
  395. //
  396. // The following table shows examples of the results for
  397. // Quo(x, y, Scale(scale), RoundHalfDown).
  398. //
  399. // x y scale result
  400. // ------------------------------
  401. // -1.8 10 1 -0.2
  402. // -1.5 10 1 -0.1
  403. // -1.2 10 1 -0.1
  404. // -1.0 10 1 -0.1
  405. // -0.8 10 1 -0.1
  406. // -0.5 10 1 -0.0
  407. // -0.2 10 1 -0.0
  408. // 0.0 10 1 0.0
  409. // 0.2 10 1 0.0
  410. // 0.5 10 1 0.0
  411. // 0.8 10 1 0.1
  412. // 1.0 10 1 0.1
  413. // 1.2 10 1 0.1
  414. // 1.5 10 1 0.1
  415. // 1.8 10 1 0.2
  416. //
  417. var RoundHalfDown Rounder = roundHalfDown
  418. // RoundHalfUp rounds to the nearest Dec, and when the remainder is 1/2, it
  419. // rounds to the Dec with the greater absolute value.
  420. //
  421. // The following table shows examples of the results for
  422. // Quo(x, y, Scale(scale), RoundHalfUp).
  423. //
  424. // x y scale result
  425. // ------------------------------
  426. // -1.8 10 1 -0.2
  427. // -1.5 10 1 -0.2
  428. // -1.2 10 1 -0.1
  429. // -1.0 10 1 -0.1
  430. // -0.8 10 1 -0.1
  431. // -0.5 10 1 -0.1
  432. // -0.2 10 1 -0.0
  433. // 0.0 10 1 0.0
  434. // 0.2 10 1 0.0
  435. // 0.5 10 1 0.1
  436. // 0.8 10 1 0.1
  437. // 1.0 10 1 0.1
  438. // 1.2 10 1 0.1
  439. // 1.5 10 1 0.2
  440. // 1.8 10 1 0.2
  441. //
  442. var RoundHalfUp Rounder = roundHalfUp
  443. // RoundFloor rounds towards negative infinity; that is, returns the greatest
  444. // Dec not exceeding the result represented by quo and rem.
  445. //
  446. // The following table shows examples of the results for
  447. // Quo(x, y, Scale(scale), RoundFloor).
  448. //
  449. // x y scale result
  450. // ------------------------------
  451. // -1.8 10 1 -0.2
  452. // -1.5 10 1 -0.2
  453. // -1.2 10 1 -0.2
  454. // -1.0 10 1 -0.1
  455. // -0.8 10 1 -0.1
  456. // -0.5 10 1 -0.1
  457. // -0.2 10 1 -0.1
  458. // 0.0 10 1 0.0
  459. // 0.2 10 1 0.0
  460. // 0.5 10 1 0.0
  461. // 0.8 10 1 0.0
  462. // 1.0 10 1 0.1
  463. // 1.2 10 1 0.1
  464. // 1.5 10 1 0.1
  465. // 1.8 10 1 0.1
  466. //
  467. var RoundFloor Rounder = roundFloor
  468. // RoundCeil rounds towards positive infinity; that is, returns the
  469. // smallest Dec not smaller than the result represented by quo and rem.
  470. //
  471. // The following table shows examples of the results for
  472. // Quo(x, y, Scale(scale), RoundCeil).
  473. //
  474. // x y scale result
  475. // ------------------------------
  476. // -1.8 10 1 -0.1
  477. // -1.5 10 1 -0.1
  478. // -1.2 10 1 -0.1
  479. // -1.0 10 1 -0.1
  480. // -0.8 10 1 -0.0
  481. // -0.5 10 1 -0.0
  482. // -0.2 10 1 -0.0
  483. // 0.0 10 1 0.0
  484. // 0.2 10 1 0.1
  485. // 0.5 10 1 0.1
  486. // 0.8 10 1 0.1
  487. // 1.0 10 1 0.1
  488. // 1.2 10 1 0.2
  489. // 1.5 10 1 0.2
  490. // 1.8 10 1 0.2
  491. //
  492. var RoundCeil Rounder = roundCeil
  493. var intSign = []*big.Int{big.NewInt(-1), big.NewInt(0), big.NewInt(1)}
  494. var roundExact = rounder{true,
  495. func(z, q *Dec, rA, rB *big.Int) *Dec {
  496. if rA.Sign() != 0 {
  497. return nil
  498. }
  499. return z.move(q)
  500. }}
  501. var roundDown = rounder{false,
  502. func(z, q *Dec, rA, rB *big.Int) *Dec {
  503. return z.move(q)
  504. }}
  505. var roundUp = rounder{true,
  506. func(z, q *Dec, rA, rB *big.Int) *Dec {
  507. z.move(q)
  508. if rA.Sign() != 0 {
  509. z.Unscaled().Add(z.Unscaled(), intSign[rA.Sign()*rB.Sign()+1])
  510. }
  511. return z
  512. }}
  513. var roundHalfDown = rounder{true,
  514. func(z, q *Dec, rA, rB *big.Int) *Dec {
  515. z.move(q)
  516. brA, brB := rA.BitLen(), rB.BitLen()
  517. if brA < brB-1 {
  518. // brA < brB-1 => |rA| < |rB/2|
  519. return z
  520. }
  521. adjust := false
  522. srA, srB := rA.Sign(), rB.Sign()
  523. s := srA * srB
  524. if brA == brB-1 {
  525. rA2 := new(big.Int).Lsh(rA, 1)
  526. if s < 0 {
  527. rA2.Neg(rA2)
  528. }
  529. if rA2.Cmp(rB)*srB > 0 {
  530. adjust = true
  531. }
  532. } else {
  533. // brA > brB-1 => |rA| > |rB/2|
  534. adjust = true
  535. }
  536. if adjust {
  537. z.Unscaled().Add(z.Unscaled(), intSign[s+1])
  538. }
  539. return z
  540. }}
  541. var roundHalfUp = rounder{true,
  542. func(z, q *Dec, rA, rB *big.Int) *Dec {
  543. z.move(q)
  544. brA, brB := rA.BitLen(), rB.BitLen()
  545. if brA < brB-1 {
  546. // brA < brB-1 => |rA| < |rB/2|
  547. return z
  548. }
  549. adjust := false
  550. srA, srB := rA.Sign(), rB.Sign()
  551. s := srA * srB
  552. if brA == brB-1 {
  553. rA2 := new(big.Int).Lsh(rA, 1)
  554. if s < 0 {
  555. rA2.Neg(rA2)
  556. }
  557. if rA2.Cmp(rB)*srB >= 0 {
  558. adjust = true
  559. }
  560. } else {
  561. // brA > brB-1 => |rA| > |rB/2|
  562. adjust = true
  563. }
  564. if adjust {
  565. z.Unscaled().Add(z.Unscaled(), intSign[s+1])
  566. }
  567. return z
  568. }}
  569. var roundFloor = rounder{true,
  570. func(z, q *Dec, rA, rB *big.Int) *Dec {
  571. z.move(q)
  572. if rA.Sign()*rB.Sign() < 0 {
  573. z.Unscaled().Add(z.Unscaled(), intSign[0])
  574. }
  575. return z
  576. }}
  577. var roundCeil = rounder{true,
  578. func(z, q *Dec, rA, rB *big.Int) *Dec {
  579. z.move(q)
  580. if rA.Sign()*rB.Sign() > 0 {
  581. z.Unscaled().Add(z.Unscaled(), intSign[2])
  582. }
  583. return z
  584. }}
  585. func upscale(a, b *Dec) (*Dec, *Dec) {
  586. if a.Scale() == b.Scale() {
  587. return a, b
  588. }
  589. if a.Scale() > b.Scale() {
  590. bb := b.rescale(a.Scale())
  591. return a, bb
  592. }
  593. aa := a.rescale(b.Scale())
  594. return aa, b
  595. }
  596. func exp10(x Scale) *big.Int {
  597. if int(x) < len(exp10cache) {
  598. return &exp10cache[int(x)]
  599. }
  600. return new(big.Int).Exp(bigInt[10], big.NewInt(int64(x)), nil)
  601. }
  602. func (x *Dec) rescale(newScale Scale) *Dec {
  603. shift := newScale - x.Scale()
  604. switch {
  605. case shift < 0:
  606. e := exp10(-shift)
  607. return NewDec(new(big.Int).Quo(x.Unscaled(), e), newScale)
  608. case shift > 0:
  609. e := exp10(shift)
  610. return NewDec(new(big.Int).Mul(x.Unscaled(), e), newScale)
  611. }
  612. return x
  613. }
  614. var zeros = []byte("00000000000000000000000000000000" +
  615. "00000000000000000000000000000000")
  616. var lzeros = Scale(len(zeros))
  617. func appendZeros(s []byte, n Scale) []byte {
  618. for i := Scale(0); i < n; i += lzeros {
  619. if n > i+lzeros {
  620. s = append(s, zeros...)
  621. } else {
  622. s = append(s, zeros[0:n-i]...)
  623. }
  624. }
  625. return s
  626. }
  627. func (x *Dec) String() string {
  628. if x == nil {
  629. return "<nil>"
  630. }
  631. scale := x.Scale()
  632. s := []byte(x.Unscaled().String())
  633. if scale <= 0 {
  634. if scale != 0 && x.unscaled.Sign() != 0 {
  635. s = appendZeros(s, -scale)
  636. }
  637. return string(s)
  638. }
  639. negbit := Scale(-((x.Sign() - 1) / 2))
  640. // scale > 0
  641. lens := Scale(len(s))
  642. if lens-negbit <= scale {
  643. ss := make([]byte, 0, scale+2)
  644. if negbit == 1 {
  645. ss = append(ss, '-')
  646. }
  647. ss = append(ss, '0', '.')
  648. ss = appendZeros(ss, scale-lens+negbit)
  649. ss = append(ss, s[negbit:]...)
  650. return string(ss)
  651. }
  652. // lens > scale
  653. ss := make([]byte, 0, lens+1)
  654. ss = append(ss, s[:lens-scale]...)
  655. ss = append(ss, '.')
  656. ss = append(ss, s[lens-scale:]...)
  657. return string(ss)
  658. }
  659. // Format is a support routine for fmt.Formatter. It accepts the decimal
  660. // formats 'd' and 'f', and handles both equivalently.
  661. // Width, precision, flags and bases 2, 8, 16 are not supported.
  662. func (x *Dec) Format(s fmt.State, ch rune) {
  663. if ch != 'd' && ch != 'f' && ch != 'v' && ch != 's' {
  664. fmt.Fprintf(s, "%%!%c(dec.Dec=%s)", ch, x.String())
  665. return
  666. }
  667. fmt.Fprintf(s, x.String())
  668. }
  669. func (z *Dec) scan(r io.RuneScanner) (*Dec, error) {
  670. unscaled := make([]byte, 0, 256) // collects chars of unscaled as bytes
  671. dp, dg := -1, -1 // indexes of decimal point, first digit
  672. loop:
  673. for {
  674. ch, _, err := r.ReadRune()
  675. if err == io.EOF {
  676. break loop
  677. }
  678. if err != nil {
  679. return nil, err
  680. }
  681. switch {
  682. case ch == '+' || ch == '-':
  683. if len(unscaled) > 0 || dp >= 0 { // must be first character
  684. r.UnreadRune()
  685. break loop
  686. }
  687. case ch == '.':
  688. if dp >= 0 {
  689. r.UnreadRune()
  690. break loop
  691. }
  692. dp = len(unscaled)
  693. continue // don't add to unscaled
  694. case ch >= '0' && ch <= '9':
  695. if dg == -1 {
  696. dg = len(unscaled)
  697. }
  698. default:
  699. r.UnreadRune()
  700. break loop
  701. }
  702. unscaled = append(unscaled, byte(ch))
  703. }
  704. if dg == -1 {
  705. return nil, fmt.Errorf("no digits read")
  706. }
  707. if dp >= 0 {
  708. z.SetScale(Scale(len(unscaled) - dp))
  709. } else {
  710. z.SetScale(0)
  711. }
  712. _, ok := z.Unscaled().SetString(string(unscaled), 10)
  713. if !ok {
  714. return nil, fmt.Errorf("invalid decimal: %s", string(unscaled))
  715. }
  716. return z, nil
  717. }
  718. // SetString sets z to the value of s, interpreted as a decimal (base 10),
  719. // and returns z and a boolean indicating success. The scale of z is the
  720. // number of digits after the decimal point (including any trailing 0s),
  721. // or 0 if there is no decimal point. If SetString fails, the value of z
  722. // is undefined but the returned value is nil.
  723. func (z *Dec) SetString(s string) (*Dec, bool) {
  724. r := strings.NewReader(s)
  725. _, err := z.scan(r)
  726. if err != nil {
  727. return nil, false
  728. }
  729. _, _, err = r.ReadRune()
  730. if err != io.EOF {
  731. return nil, false
  732. }
  733. // err == io.EOF => scan consumed all of s
  734. return z, true
  735. }
  736. // Scan is a support routine for fmt.Scanner; it sets z to the value of
  737. // the scanned number. It accepts the decimal formats 'd' and 'f', and
  738. // handles both equivalently. Bases 2, 8, 16 are not supported.
  739. // The scale of z is the number of digits after the decimal point
  740. // (including any trailing 0s), or 0 if there is no decimal point.
  741. func (z *Dec) Scan(s fmt.ScanState, ch rune) error {
  742. if ch != 'd' && ch != 'f' && ch != 's' && ch != 'v' {
  743. return fmt.Errorf("Dec.Scan: invalid verb '%c'", ch)
  744. }
  745. s.SkipSpace()
  746. _, err := z.scan(s)
  747. return err
  748. }
  749. // Gob encoding version
  750. const decGobVersion byte = 1
  751. func scaleBytes(s Scale) []byte {
  752. buf := make([]byte, scaleSize)
  753. i := scaleSize
  754. for j := 0; j < scaleSize; j++ {
  755. i--
  756. buf[i] = byte(s)
  757. s >>= 8
  758. }
  759. return buf
  760. }
  761. func scale(b []byte) (s Scale) {
  762. for j := 0; j < scaleSize; j++ {
  763. s <<= 8
  764. s |= Scale(b[j])
  765. }
  766. return
  767. }
  768. // GobEncode implements the gob.GobEncoder interface.
  769. func (x *Dec) GobEncode() ([]byte, error) {
  770. buf, err := x.Unscaled().GobEncode()
  771. if err != nil {
  772. return nil, err
  773. }
  774. buf = append(append(buf, scaleBytes(x.Scale())...), decGobVersion)
  775. return buf, nil
  776. }
  777. // GobDecode implements the gob.GobDecoder interface.
  778. func (z *Dec) GobDecode(buf []byte) error {
  779. if len(buf) == 0 {
  780. return fmt.Errorf("Dec.GobDecode: no data")
  781. }
  782. b := buf[len(buf)-1]
  783. if b != decGobVersion {
  784. return fmt.Errorf("Dec.GobDecode: encoding version %d not supported", b)
  785. }
  786. l := len(buf) - scaleSize - 1
  787. err := z.Unscaled().GobDecode(buf[:l])
  788. if err != nil {
  789. return err
  790. }
  791. z.SetScale(scale(buf[l : l+scaleSize]))
  792. return nil
  793. }