dec.go 22 KB

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