decimal.go 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379
  1. // Copyright 2009 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. // Multiprecision decimal numbers.
  5. // For floating-point formatting only; not general purpose.
  6. // Only operations are assign and (binary) left/right shift.
  7. // Can do binary floating point in multiprecision decimal precisely
  8. // because 2 divides 10; cannot do decimal floating point
  9. // in multiprecision binary precisely.
  10. package strconv
  11. type decimal struct {
  12. d [800]byte // digits
  13. nd int // number of digits used
  14. dp int // decimal point
  15. neg bool
  16. trunc bool // discarded nonzero digits beyond d[:nd]
  17. }
  18. func (a *decimal) String() string {
  19. n := 10 + a.nd
  20. if a.dp > 0 {
  21. n += a.dp
  22. }
  23. if a.dp < 0 {
  24. n += -a.dp
  25. }
  26. buf := make([]byte, n)
  27. w := 0
  28. switch {
  29. case a.nd == 0:
  30. return "0"
  31. case a.dp <= 0:
  32. // zeros fill space between decimal point and digits
  33. buf[w] = '0'
  34. w++
  35. buf[w] = '.'
  36. w++
  37. w += digitZero(buf[w : w+-a.dp])
  38. w += copy(buf[w:], a.d[0:a.nd])
  39. case a.dp < a.nd:
  40. // decimal point in middle of digits
  41. w += copy(buf[w:], a.d[0:a.dp])
  42. buf[w] = '.'
  43. w++
  44. w += copy(buf[w:], a.d[a.dp:a.nd])
  45. default:
  46. // zeros fill space between digits and decimal point
  47. w += copy(buf[w:], a.d[0:a.nd])
  48. w += digitZero(buf[w : w+a.dp-a.nd])
  49. }
  50. return string(buf[0:w])
  51. }
  52. func digitZero(dst []byte) int {
  53. for i := range dst {
  54. dst[i] = '0'
  55. }
  56. return len(dst)
  57. }
  58. // trim trailing zeros from number.
  59. // (They are meaningless; the decimal point is tracked
  60. // independent of the number of digits.)
  61. func trim(a *decimal) {
  62. for a.nd > 0 && a.d[a.nd-1] == '0' {
  63. a.nd--
  64. }
  65. if a.nd == 0 {
  66. a.dp = 0
  67. }
  68. }
  69. // Assign v to a.
  70. func (a *decimal) Assign(v uint64) {
  71. var buf [24]byte
  72. // Write reversed decimal in buf.
  73. n := 0
  74. for v > 0 {
  75. v1 := v / 10
  76. v -= 10 * v1
  77. buf[n] = byte(v + '0')
  78. n++
  79. v = v1
  80. }
  81. // Reverse again to produce forward decimal in a.d.
  82. a.nd = 0
  83. for n--; n >= 0; n-- {
  84. a.d[a.nd] = buf[n]
  85. a.nd++
  86. }
  87. a.dp = a.nd
  88. trim(a)
  89. }
  90. // Maximum shift that we can do in one pass without overflow.
  91. // Signed int has 31 bits, and we have to be able to accommodate 9<<k.
  92. const maxShift = 27
  93. // Binary shift right (* 2) by k bits. k <= maxShift to avoid overflow.
  94. func rightShift(a *decimal, k uint) {
  95. r := 0 // read pointer
  96. w := 0 // write pointer
  97. // Pick up enough leading digits to cover first shift.
  98. n := 0
  99. for ; n>>k == 0; r++ {
  100. if r >= a.nd {
  101. if n == 0 {
  102. // a == 0; shouldn't get here, but handle anyway.
  103. a.nd = 0
  104. return
  105. }
  106. for n>>k == 0 {
  107. n = n * 10
  108. r++
  109. }
  110. break
  111. }
  112. c := int(a.d[r])
  113. n = n*10 + c - '0'
  114. }
  115. a.dp -= r - 1
  116. // Pick up a digit, put down a digit.
  117. for ; r < a.nd; r++ {
  118. c := int(a.d[r])
  119. dig := n >> k
  120. n -= dig << k
  121. a.d[w] = byte(dig + '0')
  122. w++
  123. n = n*10 + c - '0'
  124. }
  125. // Put down extra digits.
  126. for n > 0 {
  127. dig := n >> k
  128. n -= dig << k
  129. if w < len(a.d) {
  130. a.d[w] = byte(dig + '0')
  131. w++
  132. } else if dig > 0 {
  133. a.trunc = true
  134. }
  135. n = n * 10
  136. }
  137. a.nd = w
  138. trim(a)
  139. }
  140. // Cheat sheet for left shift: table indexed by shift count giving
  141. // number of new digits that will be introduced by that shift.
  142. //
  143. // For example, leftcheats[4] = {2, "625"}. That means that
  144. // if we are shifting by 4 (multiplying by 16), it will add 2 digits
  145. // when the string prefix is "625" through "999", and one fewer digit
  146. // if the string prefix is "000" through "624".
  147. //
  148. // Credit for this trick goes to Ken.
  149. type leftCheat struct {
  150. delta int // number of new digits
  151. cutoff string // minus one digit if original < a.
  152. }
  153. var leftcheats = []leftCheat{
  154. // Leading digits of 1/2^i = 5^i.
  155. // 5^23 is not an exact 64-bit floating point number,
  156. // so have to use bc for the math.
  157. /*
  158. seq 27 | sed 's/^/5^/' | bc |
  159. awk 'BEGIN{ print "\tleftCheat{ 0, \"\" }," }
  160. {
  161. log2 = log(2)/log(10)
  162. printf("\tleftCheat{ %d, \"%s\" },\t// * %d\n",
  163. int(log2*NR+1), $0, 2**NR)
  164. }'
  165. */
  166. {0, ""},
  167. {1, "5"}, // * 2
  168. {1, "25"}, // * 4
  169. {1, "125"}, // * 8
  170. {2, "625"}, // * 16
  171. {2, "3125"}, // * 32
  172. {2, "15625"}, // * 64
  173. {3, "78125"}, // * 128
  174. {3, "390625"}, // * 256
  175. {3, "1953125"}, // * 512
  176. {4, "9765625"}, // * 1024
  177. {4, "48828125"}, // * 2048
  178. {4, "244140625"}, // * 4096
  179. {4, "1220703125"}, // * 8192
  180. {5, "6103515625"}, // * 16384
  181. {5, "30517578125"}, // * 32768
  182. {5, "152587890625"}, // * 65536
  183. {6, "762939453125"}, // * 131072
  184. {6, "3814697265625"}, // * 262144
  185. {6, "19073486328125"}, // * 524288
  186. {7, "95367431640625"}, // * 1048576
  187. {7, "476837158203125"}, // * 2097152
  188. {7, "2384185791015625"}, // * 4194304
  189. {7, "11920928955078125"}, // * 8388608
  190. {8, "59604644775390625"}, // * 16777216
  191. {8, "298023223876953125"}, // * 33554432
  192. {8, "1490116119384765625"}, // * 67108864
  193. {9, "7450580596923828125"}, // * 134217728
  194. }
  195. // Is the leading prefix of b lexicographically less than s?
  196. func prefixIsLessThan(b []byte, s string) bool {
  197. for i := 0; i < len(s); i++ {
  198. if i >= len(b) {
  199. return true
  200. }
  201. if b[i] != s[i] {
  202. return b[i] < s[i]
  203. }
  204. }
  205. return false
  206. }
  207. // Binary shift left (/ 2) by k bits. k <= maxShift to avoid overflow.
  208. func leftShift(a *decimal, k uint) {
  209. delta := leftcheats[k].delta
  210. if prefixIsLessThan(a.d[0:a.nd], leftcheats[k].cutoff) {
  211. delta--
  212. }
  213. r := a.nd // read index
  214. w := a.nd + delta // write index
  215. n := 0
  216. // Pick up a digit, put down a digit.
  217. for r--; r >= 0; r-- {
  218. n += (int(a.d[r]) - '0') << k
  219. quo := n / 10
  220. rem := n - 10*quo
  221. w--
  222. if w < len(a.d) {
  223. a.d[w] = byte(rem + '0')
  224. } else if rem != 0 {
  225. a.trunc = true
  226. }
  227. n = quo
  228. }
  229. // Put down extra digits.
  230. for n > 0 {
  231. quo := n / 10
  232. rem := n - 10*quo
  233. w--
  234. if w < len(a.d) {
  235. a.d[w] = byte(rem + '0')
  236. } else if rem != 0 {
  237. a.trunc = true
  238. }
  239. n = quo
  240. }
  241. a.nd += delta
  242. if a.nd >= len(a.d) {
  243. a.nd = len(a.d)
  244. }
  245. a.dp += delta
  246. trim(a)
  247. }
  248. // Binary shift left (k > 0) or right (k < 0).
  249. func (a *decimal) Shift(k int) {
  250. switch {
  251. case a.nd == 0:
  252. // nothing to do: a == 0
  253. case k > 0:
  254. for k > maxShift {
  255. leftShift(a, maxShift)
  256. k -= maxShift
  257. }
  258. leftShift(a, uint(k))
  259. case k < 0:
  260. for k < -maxShift {
  261. rightShift(a, maxShift)
  262. k += maxShift
  263. }
  264. rightShift(a, uint(-k))
  265. }
  266. }
  267. // If we chop a at nd digits, should we round up?
  268. func shouldRoundUp(a *decimal, nd int) bool {
  269. if nd < 0 || nd >= a.nd {
  270. return false
  271. }
  272. if a.d[nd] == '5' && nd+1 == a.nd { // exactly halfway - round to even
  273. // if we truncated, a little higher than what's recorded - always round up
  274. if a.trunc {
  275. return true
  276. }
  277. return nd > 0 && (a.d[nd-1]-'0')%2 != 0
  278. }
  279. // not halfway - digit tells all
  280. return a.d[nd] >= '5'
  281. }
  282. // Round a to nd digits (or fewer).
  283. // If nd is zero, it means we're rounding
  284. // just to the left of the digits, as in
  285. // 0.09 -> 0.1.
  286. func (a *decimal) Round(nd int) {
  287. if nd < 0 || nd >= a.nd {
  288. return
  289. }
  290. if shouldRoundUp(a, nd) {
  291. a.RoundUp(nd)
  292. } else {
  293. a.RoundDown(nd)
  294. }
  295. }
  296. // Round a down to nd digits (or fewer).
  297. func (a *decimal) RoundDown(nd int) {
  298. if nd < 0 || nd >= a.nd {
  299. return
  300. }
  301. a.nd = nd
  302. trim(a)
  303. }
  304. // Round a up to nd digits (or fewer).
  305. func (a *decimal) RoundUp(nd int) {
  306. if nd < 0 || nd >= a.nd {
  307. return
  308. }
  309. // round up
  310. for i := nd - 1; i >= 0; i-- {
  311. c := a.d[i]
  312. if c < '9' { // can stop after this digit
  313. a.d[i]++
  314. a.nd = i + 1
  315. return
  316. }
  317. }
  318. // Number is all 9s.
  319. // Change to single 1 with adjusted decimal point.
  320. a.d[0] = '1'
  321. a.nd = 1
  322. a.dp++
  323. }
  324. // Extract integer part, rounded appropriately.
  325. // No guarantees about overflow.
  326. func (a *decimal) RoundedInteger() uint64 {
  327. if a.dp > 20 {
  328. return 0xFFFFFFFFFFFFFFFF
  329. }
  330. var i int
  331. n := uint64(0)
  332. for i = 0; i < a.dp && i < a.nd; i++ {
  333. n = n*10 + uint64(a.d[i]-'0')
  334. }
  335. for ; i < a.dp; i++ {
  336. n *= 10
  337. }
  338. if shouldRoundUp(a, a.dp) {
  339. n++
  340. }
  341. return n
  342. }