dec.go 23 KB

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