github.com/mdempsky/go@v0.0.0-20151201204031-5dd372bd1e70/src/strconv/decimal.go (about)

     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  
     5  // Multiprecision decimal numbers.
     6  // For floating-point formatting only; not general purpose.
     7  // Only operations are assign and (binary) left/right shift.
     8  // Can do binary floating point in multiprecision decimal precisely
     9  // because 2 divides 10; cannot do decimal floating point
    10  // in multiprecision binary precisely.
    11  
    12  package strconv
    13  
    14  type decimal struct {
    15  	d     [800]byte // digits, big-endian representation
    16  	nd    int       // number of digits used
    17  	dp    int       // decimal point
    18  	neg   bool
    19  	trunc bool // discarded nonzero digits beyond d[:nd]
    20  }
    21  
    22  func (a *decimal) String() string {
    23  	n := 10 + a.nd
    24  	if a.dp > 0 {
    25  		n += a.dp
    26  	}
    27  	if a.dp < 0 {
    28  		n += -a.dp
    29  	}
    30  
    31  	buf := make([]byte, n)
    32  	w := 0
    33  	switch {
    34  	case a.nd == 0:
    35  		return "0"
    36  
    37  	case a.dp <= 0:
    38  		// zeros fill space between decimal point and digits
    39  		buf[w] = '0'
    40  		w++
    41  		buf[w] = '.'
    42  		w++
    43  		w += digitZero(buf[w : w+-a.dp])
    44  		w += copy(buf[w:], a.d[0:a.nd])
    45  
    46  	case a.dp < a.nd:
    47  		// decimal point in middle of digits
    48  		w += copy(buf[w:], a.d[0:a.dp])
    49  		buf[w] = '.'
    50  		w++
    51  		w += copy(buf[w:], a.d[a.dp:a.nd])
    52  
    53  	default:
    54  		// zeros fill space between digits and decimal point
    55  		w += copy(buf[w:], a.d[0:a.nd])
    56  		w += digitZero(buf[w : w+a.dp-a.nd])
    57  	}
    58  	return string(buf[0:w])
    59  }
    60  
    61  func digitZero(dst []byte) int {
    62  	for i := range dst {
    63  		dst[i] = '0'
    64  	}
    65  	return len(dst)
    66  }
    67  
    68  // trim trailing zeros from number.
    69  // (They are meaningless; the decimal point is tracked
    70  // independent of the number of digits.)
    71  func trim(a *decimal) {
    72  	for a.nd > 0 && a.d[a.nd-1] == '0' {
    73  		a.nd--
    74  	}
    75  	if a.nd == 0 {
    76  		a.dp = 0
    77  	}
    78  }
    79  
    80  // Assign v to a.
    81  func (a *decimal) Assign(v uint64) {
    82  	var buf [24]byte
    83  
    84  	// Write reversed decimal in buf.
    85  	n := 0
    86  	for v > 0 {
    87  		v1 := v / 10
    88  		v -= 10 * v1
    89  		buf[n] = byte(v + '0')
    90  		n++
    91  		v = v1
    92  	}
    93  
    94  	// Reverse again to produce forward decimal in a.d.
    95  	a.nd = 0
    96  	for n--; n >= 0; n-- {
    97  		a.d[a.nd] = buf[n]
    98  		a.nd++
    99  	}
   100  	a.dp = a.nd
   101  	trim(a)
   102  }
   103  
   104  // Maximum shift that we can do in one pass without overflow.
   105  // A uint has 32 or 64 bits, and we have to be able to accommodate 9<<k.
   106  const uintSize = 32 << (^uint(0) >> 63)
   107  const maxShift = uintSize - 4
   108  
   109  // Binary shift right (/ 2) by k bits.  k <= maxShift to avoid overflow.
   110  func rightShift(a *decimal, k uint) {
   111  	r := 0 // read pointer
   112  	w := 0 // write pointer
   113  
   114  	// Pick up enough leading digits to cover first shift.
   115  	var n uint
   116  	for ; n>>k == 0; r++ {
   117  		if r >= a.nd {
   118  			if n == 0 {
   119  				// a == 0; shouldn't get here, but handle anyway.
   120  				a.nd = 0
   121  				return
   122  			}
   123  			for n>>k == 0 {
   124  				n = n * 10
   125  				r++
   126  			}
   127  			break
   128  		}
   129  		c := uint(a.d[r])
   130  		n = n*10 + c - '0'
   131  	}
   132  	a.dp -= r - 1
   133  
   134  	// Pick up a digit, put down a digit.
   135  	for ; r < a.nd; r++ {
   136  		c := uint(a.d[r])
   137  		dig := n >> k
   138  		n -= dig << k
   139  		a.d[w] = byte(dig + '0')
   140  		w++
   141  		n = n*10 + c - '0'
   142  	}
   143  
   144  	// Put down extra digits.
   145  	for n > 0 {
   146  		dig := n >> k
   147  		n -= dig << k
   148  		if w < len(a.d) {
   149  			a.d[w] = byte(dig + '0')
   150  			w++
   151  		} else if dig > 0 {
   152  			a.trunc = true
   153  		}
   154  		n = n * 10
   155  	}
   156  
   157  	a.nd = w
   158  	trim(a)
   159  }
   160  
   161  // Cheat sheet for left shift: table indexed by shift count giving
   162  // number of new digits that will be introduced by that shift.
   163  //
   164  // For example, leftcheats[4] = {2, "625"}.  That means that
   165  // if we are shifting by 4 (multiplying by 16), it will add 2 digits
   166  // when the string prefix is "625" through "999", and one fewer digit
   167  // if the string prefix is "000" through "624".
   168  //
   169  // Credit for this trick goes to Ken.
   170  
   171  type leftCheat struct {
   172  	delta  int    // number of new digits
   173  	cutoff string // minus one digit if original < a.
   174  }
   175  
   176  var leftcheats = []leftCheat{
   177  	// Leading digits of 1/2^i = 5^i.
   178  	// 5^23 is not an exact 64-bit floating point number,
   179  	// so have to use bc for the math.
   180  	// Go up to 60 to be large enough for 32bit and 64bit platforms.
   181  	/*
   182  		seq 60 | sed 's/^/5^/' | bc |
   183  		awk 'BEGIN{ print "\t{ 0, \"\" }," }
   184  		{
   185  			log2 = log(2)/log(10)
   186  			printf("\t{ %d, \"%s\" },\t// * %d\n",
   187  				int(log2*NR+1), $0, 2**NR)
   188  		}'
   189  	*/
   190  	{0, ""},
   191  	{1, "5"},                                           // * 2
   192  	{1, "25"},                                          // * 4
   193  	{1, "125"},                                         // * 8
   194  	{2, "625"},                                         // * 16
   195  	{2, "3125"},                                        // * 32
   196  	{2, "15625"},                                       // * 64
   197  	{3, "78125"},                                       // * 128
   198  	{3, "390625"},                                      // * 256
   199  	{3, "1953125"},                                     // * 512
   200  	{4, "9765625"},                                     // * 1024
   201  	{4, "48828125"},                                    // * 2048
   202  	{4, "244140625"},                                   // * 4096
   203  	{4, "1220703125"},                                  // * 8192
   204  	{5, "6103515625"},                                  // * 16384
   205  	{5, "30517578125"},                                 // * 32768
   206  	{5, "152587890625"},                                // * 65536
   207  	{6, "762939453125"},                                // * 131072
   208  	{6, "3814697265625"},                               // * 262144
   209  	{6, "19073486328125"},                              // * 524288
   210  	{7, "95367431640625"},                              // * 1048576
   211  	{7, "476837158203125"},                             // * 2097152
   212  	{7, "2384185791015625"},                            // * 4194304
   213  	{7, "11920928955078125"},                           // * 8388608
   214  	{8, "59604644775390625"},                           // * 16777216
   215  	{8, "298023223876953125"},                          // * 33554432
   216  	{8, "1490116119384765625"},                         // * 67108864
   217  	{9, "7450580596923828125"},                         // * 134217728
   218  	{9, "37252902984619140625"},                        // * 268435456
   219  	{9, "186264514923095703125"},                       // * 536870912
   220  	{10, "931322574615478515625"},                      // * 1073741824
   221  	{10, "4656612873077392578125"},                     // * 2147483648
   222  	{10, "23283064365386962890625"},                    // * 4294967296
   223  	{10, "116415321826934814453125"},                   // * 8589934592
   224  	{11, "582076609134674072265625"},                   // * 17179869184
   225  	{11, "2910383045673370361328125"},                  // * 34359738368
   226  	{11, "14551915228366851806640625"},                 // * 68719476736
   227  	{12, "72759576141834259033203125"},                 // * 137438953472
   228  	{12, "363797880709171295166015625"},                // * 274877906944
   229  	{12, "1818989403545856475830078125"},               // * 549755813888
   230  	{13, "9094947017729282379150390625"},               // * 1099511627776
   231  	{13, "45474735088646411895751953125"},              // * 2199023255552
   232  	{13, "227373675443232059478759765625"},             // * 4398046511104
   233  	{13, "1136868377216160297393798828125"},            // * 8796093022208
   234  	{14, "5684341886080801486968994140625"},            // * 17592186044416
   235  	{14, "28421709430404007434844970703125"},           // * 35184372088832
   236  	{14, "142108547152020037174224853515625"},          // * 70368744177664
   237  	{15, "710542735760100185871124267578125"},          // * 140737488355328
   238  	{15, "3552713678800500929355621337890625"},         // * 281474976710656
   239  	{15, "17763568394002504646778106689453125"},        // * 562949953421312
   240  	{16, "88817841970012523233890533447265625"},        // * 1125899906842624
   241  	{16, "444089209850062616169452667236328125"},       // * 2251799813685248
   242  	{16, "2220446049250313080847263336181640625"},      // * 4503599627370496
   243  	{16, "11102230246251565404236316680908203125"},     // * 9007199254740992
   244  	{17, "55511151231257827021181583404541015625"},     // * 18014398509481984
   245  	{17, "277555756156289135105907917022705078125"},    // * 36028797018963968
   246  	{17, "1387778780781445675529539585113525390625"},   // * 72057594037927936
   247  	{18, "6938893903907228377647697925567626953125"},   // * 144115188075855872
   248  	{18, "34694469519536141888238489627838134765625"},  // * 288230376151711744
   249  	{18, "173472347597680709441192448139190673828125"}, // * 576460752303423488
   250  	{19, "867361737988403547205962240695953369140625"}, // * 1152921504606846976
   251  }
   252  
   253  // Is the leading prefix of b lexicographically less than s?
   254  func prefixIsLessThan(b []byte, s string) bool {
   255  	for i := 0; i < len(s); i++ {
   256  		if i >= len(b) {
   257  			return true
   258  		}
   259  		if b[i] != s[i] {
   260  			return b[i] < s[i]
   261  		}
   262  	}
   263  	return false
   264  }
   265  
   266  // Binary shift left (* 2) by k bits.  k <= maxShift to avoid overflow.
   267  func leftShift(a *decimal, k uint) {
   268  	delta := leftcheats[k].delta
   269  	if prefixIsLessThan(a.d[0:a.nd], leftcheats[k].cutoff) {
   270  		delta--
   271  	}
   272  
   273  	r := a.nd         // read index
   274  	w := a.nd + delta // write index
   275  
   276  	// Pick up a digit, put down a digit.
   277  	var n uint
   278  	for r--; r >= 0; r-- {
   279  		n += (uint(a.d[r]) - '0') << k
   280  		quo := n / 10
   281  		rem := n - 10*quo
   282  		w--
   283  		if w < len(a.d) {
   284  			a.d[w] = byte(rem + '0')
   285  		} else if rem != 0 {
   286  			a.trunc = true
   287  		}
   288  		n = quo
   289  	}
   290  
   291  	// Put down extra digits.
   292  	for n > 0 {
   293  		quo := n / 10
   294  		rem := n - 10*quo
   295  		w--
   296  		if w < len(a.d) {
   297  			a.d[w] = byte(rem + '0')
   298  		} else if rem != 0 {
   299  			a.trunc = true
   300  		}
   301  		n = quo
   302  	}
   303  
   304  	a.nd += delta
   305  	if a.nd >= len(a.d) {
   306  		a.nd = len(a.d)
   307  	}
   308  	a.dp += delta
   309  	trim(a)
   310  }
   311  
   312  // Binary shift left (k > 0) or right (k < 0).
   313  func (a *decimal) Shift(k int) {
   314  	switch {
   315  	case a.nd == 0:
   316  		// nothing to do: a == 0
   317  	case k > 0:
   318  		for k > maxShift {
   319  			leftShift(a, maxShift)
   320  			k -= maxShift
   321  		}
   322  		leftShift(a, uint(k))
   323  	case k < 0:
   324  		for k < -maxShift {
   325  			rightShift(a, maxShift)
   326  			k += maxShift
   327  		}
   328  		rightShift(a, uint(-k))
   329  	}
   330  }
   331  
   332  // If we chop a at nd digits, should we round up?
   333  func shouldRoundUp(a *decimal, nd int) bool {
   334  	if nd < 0 || nd >= a.nd {
   335  		return false
   336  	}
   337  	if a.d[nd] == '5' && nd+1 == a.nd { // exactly halfway - round to even
   338  		// if we truncated, a little higher than what's recorded - always round up
   339  		if a.trunc {
   340  			return true
   341  		}
   342  		return nd > 0 && (a.d[nd-1]-'0')%2 != 0
   343  	}
   344  	// not halfway - digit tells all
   345  	return a.d[nd] >= '5'
   346  }
   347  
   348  // Round a to nd digits (or fewer).
   349  // If nd is zero, it means we're rounding
   350  // just to the left of the digits, as in
   351  // 0.09 -> 0.1.
   352  func (a *decimal) Round(nd int) {
   353  	if nd < 0 || nd >= a.nd {
   354  		return
   355  	}
   356  	if shouldRoundUp(a, nd) {
   357  		a.RoundUp(nd)
   358  	} else {
   359  		a.RoundDown(nd)
   360  	}
   361  }
   362  
   363  // Round a down to nd digits (or fewer).
   364  func (a *decimal) RoundDown(nd int) {
   365  	if nd < 0 || nd >= a.nd {
   366  		return
   367  	}
   368  	a.nd = nd
   369  	trim(a)
   370  }
   371  
   372  // Round a up to nd digits (or fewer).
   373  func (a *decimal) RoundUp(nd int) {
   374  	if nd < 0 || nd >= a.nd {
   375  		return
   376  	}
   377  
   378  	// round up
   379  	for i := nd - 1; i >= 0; i-- {
   380  		c := a.d[i]
   381  		if c < '9' { // can stop after this digit
   382  			a.d[i]++
   383  			a.nd = i + 1
   384  			return
   385  		}
   386  	}
   387  
   388  	// Number is all 9s.
   389  	// Change to single 1 with adjusted decimal point.
   390  	a.d[0] = '1'
   391  	a.nd = 1
   392  	a.dp++
   393  }
   394  
   395  // Extract integer part, rounded appropriately.
   396  // No guarantees about overflow.
   397  func (a *decimal) RoundedInteger() uint64 {
   398  	if a.dp > 20 {
   399  		return 0xFFFFFFFFFFFFFFFF
   400  	}
   401  	var i int
   402  	n := uint64(0)
   403  	for i = 0; i < a.dp && i < a.nd; i++ {
   404  		n = n*10 + uint64(a.d[i]-'0')
   405  	}
   406  	for ; i < a.dp; i++ {
   407  		n *= 10
   408  	}
   409  	if shouldRoundUp(a, a.dp) {
   410  		n++
   411  	}
   412  	return n
   413  }