1/**
2 *  Copyright 2014 Paul Querna
3 *
4 *  Licensed under the Apache License, Version 2.0 (the "License");
5 *  you may not use this file except in compliance with the License.
6 *  You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 *  Unless required by applicable law or agreed to in writing, software
11 *  distributed under the License is distributed on an "AS IS" BASIS,
12 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 *  See the License for the specific language governing permissions and
14 *  limitations under the License.
15 *
16 */
17
18/* Portions of this file are on Go stdlib's strconv/atof.go */
19
20// Copyright 2009 The Go Authors. All rights reserved.
21// Use of this source code is governed by a BSD-style
22// license that can be found in the LICENSE file.
23
24package internal
25
26// decimal to binary floating point conversion.
27// Algorithm:
28//   1) Store input in multiprecision decimal.
29//   2) Multiply/divide decimal by powers of two until in range [0.5, 1)
30//   3) Multiply by 2^precision and round to get mantissa.
31
32import "math"
33
34var optimize = true // can change for testing
35
36func equalIgnoreCase(s1 []byte, s2 []byte) bool {
37	if len(s1) != len(s2) {
38		return false
39	}
40	for i := 0; i < len(s1); i++ {
41		c1 := s1[i]
42		if 'A' <= c1 && c1 <= 'Z' {
43			c1 += 'a' - 'A'
44		}
45		c2 := s2[i]
46		if 'A' <= c2 && c2 <= 'Z' {
47			c2 += 'a' - 'A'
48		}
49		if c1 != c2 {
50			return false
51		}
52	}
53	return true
54}
55
56func special(s []byte) (f float64, ok bool) {
57	if len(s) == 0 {
58		return
59	}
60	switch s[0] {
61	default:
62		return
63	case '+':
64		if equalIgnoreCase(s, []byte("+inf")) || equalIgnoreCase(s, []byte("+infinity")) {
65			return math.Inf(1), true
66		}
67	case '-':
68		if equalIgnoreCase(s, []byte("-inf")) || equalIgnoreCase(s, []byte("-infinity")) {
69			return math.Inf(-1), true
70		}
71	case 'n', 'N':
72		if equalIgnoreCase(s, []byte("nan")) {
73			return math.NaN(), true
74		}
75	case 'i', 'I':
76		if equalIgnoreCase(s, []byte("inf")) || equalIgnoreCase(s, []byte("infinity")) {
77			return math.Inf(1), true
78		}
79	}
80	return
81}
82
83func (b *decimal) set(s []byte) (ok bool) {
84	i := 0
85	b.neg = false
86	b.trunc = false
87
88	// optional sign
89	if i >= len(s) {
90		return
91	}
92	switch {
93	case s[i] == '+':
94		i++
95	case s[i] == '-':
96		b.neg = true
97		i++
98	}
99
100	// digits
101	sawdot := false
102	sawdigits := false
103	for ; i < len(s); i++ {
104		switch {
105		case s[i] == '.':
106			if sawdot {
107				return
108			}
109			sawdot = true
110			b.dp = b.nd
111			continue
112
113		case '0' <= s[i] && s[i] <= '9':
114			sawdigits = true
115			if s[i] == '0' && b.nd == 0 { // ignore leading zeros
116				b.dp--
117				continue
118			}
119			if b.nd < len(b.d) {
120				b.d[b.nd] = s[i]
121				b.nd++
122			} else if s[i] != '0' {
123				b.trunc = true
124			}
125			continue
126		}
127		break
128	}
129	if !sawdigits {
130		return
131	}
132	if !sawdot {
133		b.dp = b.nd
134	}
135
136	// optional exponent moves decimal point.
137	// if we read a very large, very long number,
138	// just be sure to move the decimal point by
139	// a lot (say, 100000).  it doesn't matter if it's
140	// not the exact number.
141	if i < len(s) && (s[i] == 'e' || s[i] == 'E') {
142		i++
143		if i >= len(s) {
144			return
145		}
146		esign := 1
147		if s[i] == '+' {
148			i++
149		} else if s[i] == '-' {
150			i++
151			esign = -1
152		}
153		if i >= len(s) || s[i] < '0' || s[i] > '9' {
154			return
155		}
156		e := 0
157		for ; i < len(s) && '0' <= s[i] && s[i] <= '9'; i++ {
158			if e < 10000 {
159				e = e*10 + int(s[i]) - '0'
160			}
161		}
162		b.dp += e * esign
163	}
164
165	if i != len(s) {
166		return
167	}
168
169	ok = true
170	return
171}
172
173// readFloat reads a decimal mantissa and exponent from a float
174// string representation. It sets ok to false if the number could
175// not fit return types or is invalid.
176func readFloat(s []byte) (mantissa uint64, exp int, neg, trunc, ok bool) {
177	const uint64digits = 19
178	i := 0
179
180	// optional sign
181	if i >= len(s) {
182		return
183	}
184	switch {
185	case s[i] == '+':
186		i++
187	case s[i] == '-':
188		neg = true
189		i++
190	}
191
192	// digits
193	sawdot := false
194	sawdigits := false
195	nd := 0
196	ndMant := 0
197	dp := 0
198	for ; i < len(s); i++ {
199		switch c := s[i]; true {
200		case c == '.':
201			if sawdot {
202				return
203			}
204			sawdot = true
205			dp = nd
206			continue
207
208		case '0' <= c && c <= '9':
209			sawdigits = true
210			if c == '0' && nd == 0 { // ignore leading zeros
211				dp--
212				continue
213			}
214			nd++
215			if ndMant < uint64digits {
216				mantissa *= 10
217				mantissa += uint64(c - '0')
218				ndMant++
219			} else if s[i] != '0' {
220				trunc = true
221			}
222			continue
223		}
224		break
225	}
226	if !sawdigits {
227		return
228	}
229	if !sawdot {
230		dp = nd
231	}
232
233	// optional exponent moves decimal point.
234	// if we read a very large, very long number,
235	// just be sure to move the decimal point by
236	// a lot (say, 100000).  it doesn't matter if it's
237	// not the exact number.
238	if i < len(s) && (s[i] == 'e' || s[i] == 'E') {
239		i++
240		if i >= len(s) {
241			return
242		}
243		esign := 1
244		if s[i] == '+' {
245			i++
246		} else if s[i] == '-' {
247			i++
248			esign = -1
249		}
250		if i >= len(s) || s[i] < '0' || s[i] > '9' {
251			return
252		}
253		e := 0
254		for ; i < len(s) && '0' <= s[i] && s[i] <= '9'; i++ {
255			if e < 10000 {
256				e = e*10 + int(s[i]) - '0'
257			}
258		}
259		dp += e * esign
260	}
261
262	if i != len(s) {
263		return
264	}
265
266	exp = dp - ndMant
267	ok = true
268	return
269
270}
271
272// decimal power of ten to binary power of two.
273var powtab = []int{1, 3, 6, 9, 13, 16, 19, 23, 26}
274
275func (d *decimal) floatBits(flt *floatInfo) (b uint64, overflow bool) {
276	var exp int
277	var mant uint64
278
279	// Zero is always a special case.
280	if d.nd == 0 {
281		mant = 0
282		exp = flt.bias
283		goto out
284	}
285
286	// Obvious overflow/underflow.
287	// These bounds are for 64-bit floats.
288	// Will have to change if we want to support 80-bit floats in the future.
289	if d.dp > 310 {
290		goto overflow
291	}
292	if d.dp < -330 {
293		// zero
294		mant = 0
295		exp = flt.bias
296		goto out
297	}
298
299	// Scale by powers of two until in range [0.5, 1.0)
300	exp = 0
301	for d.dp > 0 {
302		var n int
303		if d.dp >= len(powtab) {
304			n = 27
305		} else {
306			n = powtab[d.dp]
307		}
308		d.Shift(-n)
309		exp += n
310	}
311	for d.dp < 0 || d.dp == 0 && d.d[0] < '5' {
312		var n int
313		if -d.dp >= len(powtab) {
314			n = 27
315		} else {
316			n = powtab[-d.dp]
317		}
318		d.Shift(n)
319		exp -= n
320	}
321
322	// Our range is [0.5,1) but floating point range is [1,2).
323	exp--
324
325	// Minimum representable exponent is flt.bias+1.
326	// If the exponent is smaller, move it up and
327	// adjust d accordingly.
328	if exp < flt.bias+1 {
329		n := flt.bias + 1 - exp
330		d.Shift(-n)
331		exp += n
332	}
333
334	if exp-flt.bias >= 1<<flt.expbits-1 {
335		goto overflow
336	}
337
338	// Extract 1+flt.mantbits bits.
339	d.Shift(int(1 + flt.mantbits))
340	mant = d.RoundedInteger()
341
342	// Rounding might have added a bit; shift down.
343	if mant == 2<<flt.mantbits {
344		mant >>= 1
345		exp++
346		if exp-flt.bias >= 1<<flt.expbits-1 {
347			goto overflow
348		}
349	}
350
351	// Denormalized?
352	if mant&(1<<flt.mantbits) == 0 {
353		exp = flt.bias
354	}
355	goto out
356
357overflow:
358	// ±Inf
359	mant = 0
360	exp = 1<<flt.expbits - 1 + flt.bias
361	overflow = true
362
363out:
364	// Assemble bits.
365	bits := mant & (uint64(1)<<flt.mantbits - 1)
366	bits |= uint64((exp-flt.bias)&(1<<flt.expbits-1)) << flt.mantbits
367	if d.neg {
368		bits |= 1 << flt.mantbits << flt.expbits
369	}
370	return bits, overflow
371}
372
373// Exact powers of 10.
374var float64pow10 = []float64{
375	1e0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9,
376	1e10, 1e11, 1e12, 1e13, 1e14, 1e15, 1e16, 1e17, 1e18, 1e19,
377	1e20, 1e21, 1e22,
378}
379var float32pow10 = []float32{1e0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9, 1e10}
380
381// If possible to convert decimal representation to 64-bit float f exactly,
382// entirely in floating-point math, do so, avoiding the expense of decimalToFloatBits.
383// Three common cases:
384//	value is exact integer
385//	value is exact integer * exact power of ten
386//	value is exact integer / exact power of ten
387// These all produce potentially inexact but correctly rounded answers.
388func atof64exact(mantissa uint64, exp int, neg bool) (f float64, ok bool) {
389	if mantissa>>float64info.mantbits != 0 {
390		return
391	}
392	f = float64(mantissa)
393	if neg {
394		f = -f
395	}
396	switch {
397	case exp == 0:
398		// an integer.
399		return f, true
400	// Exact integers are <= 10^15.
401	// Exact powers of ten are <= 10^22.
402	case exp > 0 && exp <= 15+22: // int * 10^k
403		// If exponent is big but number of digits is not,
404		// can move a few zeros into the integer part.
405		if exp > 22 {
406			f *= float64pow10[exp-22]
407			exp = 22
408		}
409		if f > 1e15 || f < -1e15 {
410			// the exponent was really too large.
411			return
412		}
413		return f * float64pow10[exp], true
414	case exp < 0 && exp >= -22: // int / 10^k
415		return f / float64pow10[-exp], true
416	}
417	return
418}
419
420// If possible to compute mantissa*10^exp to 32-bit float f exactly,
421// entirely in floating-point math, do so, avoiding the machinery above.
422func atof32exact(mantissa uint64, exp int, neg bool) (f float32, ok bool) {
423	if mantissa>>float32info.mantbits != 0 {
424		return
425	}
426	f = float32(mantissa)
427	if neg {
428		f = -f
429	}
430	switch {
431	case exp == 0:
432		return f, true
433	// Exact integers are <= 10^7.
434	// Exact powers of ten are <= 10^10.
435	case exp > 0 && exp <= 7+10: // int * 10^k
436		// If exponent is big but number of digits is not,
437		// can move a few zeros into the integer part.
438		if exp > 10 {
439			f *= float32pow10[exp-10]
440			exp = 10
441		}
442		if f > 1e7 || f < -1e7 {
443			// the exponent was really too large.
444			return
445		}
446		return f * float32pow10[exp], true
447	case exp < 0 && exp >= -10: // int / 10^k
448		return f / float32pow10[-exp], true
449	}
450	return
451}
452
453const fnParseFloat = "ParseFloat"
454
455func atof32(s []byte) (f float32, err error) {
456	if val, ok := special(s); ok {
457		return float32(val), nil
458	}
459
460	if optimize {
461		// Parse mantissa and exponent.
462		mantissa, exp, neg, trunc, ok := readFloat(s)
463		if ok {
464			// Try pure floating-point arithmetic conversion.
465			if !trunc {
466				if f, ok := atof32exact(mantissa, exp, neg); ok {
467					return f, nil
468				}
469			}
470			// Try another fast path.
471			ext := new(extFloat)
472			if ok := ext.AssignDecimal(mantissa, exp, neg, trunc, &float32info); ok {
473				b, ovf := ext.floatBits(&float32info)
474				f = math.Float32frombits(uint32(b))
475				if ovf {
476					err = rangeError(fnParseFloat, string(s))
477				}
478				return f, err
479			}
480		}
481	}
482	var d decimal
483	if !d.set(s) {
484		return 0, syntaxError(fnParseFloat, string(s))
485	}
486	b, ovf := d.floatBits(&float32info)
487	f = math.Float32frombits(uint32(b))
488	if ovf {
489		err = rangeError(fnParseFloat, string(s))
490	}
491	return f, err
492}
493
494func atof64(s []byte) (f float64, err error) {
495	if val, ok := special(s); ok {
496		return val, nil
497	}
498
499	if optimize {
500		// Parse mantissa and exponent.
501		mantissa, exp, neg, trunc, ok := readFloat(s)
502		if ok {
503			// Try pure floating-point arithmetic conversion.
504			if !trunc {
505				if f, ok := atof64exact(mantissa, exp, neg); ok {
506					return f, nil
507				}
508			}
509			// Try another fast path.
510			ext := new(extFloat)
511			if ok := ext.AssignDecimal(mantissa, exp, neg, trunc, &float64info); ok {
512				b, ovf := ext.floatBits(&float64info)
513				f = math.Float64frombits(b)
514				if ovf {
515					err = rangeError(fnParseFloat, string(s))
516				}
517				return f, err
518			}
519		}
520	}
521	var d decimal
522	if !d.set(s) {
523		return 0, syntaxError(fnParseFloat, string(s))
524	}
525	b, ovf := d.floatBits(&float64info)
526	f = math.Float64frombits(b)
527	if ovf {
528		err = rangeError(fnParseFloat, string(s))
529	}
530	return f, err
531}
532
533// ParseFloat converts the string s to a floating-point number
534// with the precision specified by bitSize: 32 for float32, or 64 for float64.
535// When bitSize=32, the result still has type float64, but it will be
536// convertible to float32 without changing its value.
537//
538// If s is well-formed and near a valid floating point number,
539// ParseFloat returns the nearest floating point number rounded
540// using IEEE754 unbiased rounding.
541//
542// The errors that ParseFloat returns have concrete type *NumError
543// and include err.Num = s.
544//
545// If s is not syntactically well-formed, ParseFloat returns err.Err = ErrSyntax.
546//
547// If s is syntactically well-formed but is more than 1/2 ULP
548// away from the largest floating point number of the given size,
549// ParseFloat returns f = ±Inf, err.Err = ErrRange.
550func ParseFloat(s []byte, bitSize int) (f float64, err error) {
551	if bitSize == 32 {
552		f1, err1 := atof32(s)
553		return float64(f1), err1
554	}
555	f1, err1 := atof64(s)
556	return f1, err1
557}
558
559// oroginal: strconv/decimal.go, but not exported, and needed for PareFloat.
560
561// Copyright 2009 The Go Authors. All rights reserved.
562// Use of this source code is governed by a BSD-style
563// license that can be found in the LICENSE file.
564
565// Multiprecision decimal numbers.
566// For floating-point formatting only; not general purpose.
567// Only operations are assign and (binary) left/right shift.
568// Can do binary floating point in multiprecision decimal precisely
569// because 2 divides 10; cannot do decimal floating point
570// in multiprecision binary precisely.
571
572type decimal struct {
573	d     [800]byte // digits
574	nd    int       // number of digits used
575	dp    int       // decimal point
576	neg   bool
577	trunc bool // discarded nonzero digits beyond d[:nd]
578}
579
580func (a *decimal) String() string {
581	n := 10 + a.nd
582	if a.dp > 0 {
583		n += a.dp
584	}
585	if a.dp < 0 {
586		n += -a.dp
587	}
588
589	buf := make([]byte, n)
590	w := 0
591	switch {
592	case a.nd == 0:
593		return "0"
594
595	case a.dp <= 0:
596		// zeros fill space between decimal point and digits
597		buf[w] = '0'
598		w++
599		buf[w] = '.'
600		w++
601		w += digitZero(buf[w : w+-a.dp])
602		w += copy(buf[w:], a.d[0:a.nd])
603
604	case a.dp < a.nd:
605		// decimal point in middle of digits
606		w += copy(buf[w:], a.d[0:a.dp])
607		buf[w] = '.'
608		w++
609		w += copy(buf[w:], a.d[a.dp:a.nd])
610
611	default:
612		// zeros fill space between digits and decimal point
613		w += copy(buf[w:], a.d[0:a.nd])
614		w += digitZero(buf[w : w+a.dp-a.nd])
615	}
616	return string(buf[0:w])
617}
618
619func digitZero(dst []byte) int {
620	for i := range dst {
621		dst[i] = '0'
622	}
623	return len(dst)
624}
625
626// trim trailing zeros from number.
627// (They are meaningless; the decimal point is tracked
628// independent of the number of digits.)
629func trim(a *decimal) {
630	for a.nd > 0 && a.d[a.nd-1] == '0' {
631		a.nd--
632	}
633	if a.nd == 0 {
634		a.dp = 0
635	}
636}
637
638// Assign v to a.
639func (a *decimal) Assign(v uint64) {
640	var buf [24]byte
641
642	// Write reversed decimal in buf.
643	n := 0
644	for v > 0 {
645		v1 := v / 10
646		v -= 10 * v1
647		buf[n] = byte(v + '0')
648		n++
649		v = v1
650	}
651
652	// Reverse again to produce forward decimal in a.d.
653	a.nd = 0
654	for n--; n >= 0; n-- {
655		a.d[a.nd] = buf[n]
656		a.nd++
657	}
658	a.dp = a.nd
659	trim(a)
660}
661
662// Maximum shift that we can do in one pass without overflow.
663// Signed int has 31 bits, and we have to be able to accommodate 9<<k.
664const maxShift = 27
665
666// Binary shift right (* 2) by k bits.  k <= maxShift to avoid overflow.
667func rightShift(a *decimal, k uint) {
668	r := 0 // read pointer
669	w := 0 // write pointer
670
671	// Pick up enough leading digits to cover first shift.
672	n := 0
673	for ; n>>k == 0; r++ {
674		if r >= a.nd {
675			if n == 0 {
676				// a == 0; shouldn't get here, but handle anyway.
677				a.nd = 0
678				return
679			}
680			for n>>k == 0 {
681				n = n * 10
682				r++
683			}
684			break
685		}
686		c := int(a.d[r])
687		n = n*10 + c - '0'
688	}
689	a.dp -= r - 1
690
691	// Pick up a digit, put down a digit.
692	for ; r < a.nd; r++ {
693		c := int(a.d[r])
694		dig := n >> k
695		n -= dig << k
696		a.d[w] = byte(dig + '0')
697		w++
698		n = n*10 + c - '0'
699	}
700
701	// Put down extra digits.
702	for n > 0 {
703		dig := n >> k
704		n -= dig << k
705		if w < len(a.d) {
706			a.d[w] = byte(dig + '0')
707			w++
708		} else if dig > 0 {
709			a.trunc = true
710		}
711		n = n * 10
712	}
713
714	a.nd = w
715	trim(a)
716}
717
718// Cheat sheet for left shift: table indexed by shift count giving
719// number of new digits that will be introduced by that shift.
720//
721// For example, leftcheats[4] = {2, "625"}.  That means that
722// if we are shifting by 4 (multiplying by 16), it will add 2 digits
723// when the string prefix is "625" through "999", and one fewer digit
724// if the string prefix is "000" through "624".
725//
726// Credit for this trick goes to Ken.
727
728type leftCheat struct {
729	delta  int    // number of new digits
730	cutoff string //   minus one digit if original < a.
731}
732
733var leftcheats = []leftCheat{
734	// Leading digits of 1/2^i = 5^i.
735	// 5^23 is not an exact 64-bit floating point number,
736	// so have to use bc for the math.
737	/*
738		seq 27 | sed 's/^/5^/' | bc |
739		awk 'BEGIN{ print "\tleftCheat{ 0, \"\" }," }
740		{
741			log2 = log(2)/log(10)
742			printf("\tleftCheat{ %d, \"%s\" },\t// * %d\n",
743				int(log2*NR+1), $0, 2**NR)
744		}'
745	*/
746	{0, ""},
747	{1, "5"},                   // * 2
748	{1, "25"},                  // * 4
749	{1, "125"},                 // * 8
750	{2, "625"},                 // * 16
751	{2, "3125"},                // * 32
752	{2, "15625"},               // * 64
753	{3, "78125"},               // * 128
754	{3, "390625"},              // * 256
755	{3, "1953125"},             // * 512
756	{4, "9765625"},             // * 1024
757	{4, "48828125"},            // * 2048
758	{4, "244140625"},           // * 4096
759	{4, "1220703125"},          // * 8192
760	{5, "6103515625"},          // * 16384
761	{5, "30517578125"},         // * 32768
762	{5, "152587890625"},        // * 65536
763	{6, "762939453125"},        // * 131072
764	{6, "3814697265625"},       // * 262144
765	{6, "19073486328125"},      // * 524288
766	{7, "95367431640625"},      // * 1048576
767	{7, "476837158203125"},     // * 2097152
768	{7, "2384185791015625"},    // * 4194304
769	{7, "11920928955078125"},   // * 8388608
770	{8, "59604644775390625"},   // * 16777216
771	{8, "298023223876953125"},  // * 33554432
772	{8, "1490116119384765625"}, // * 67108864
773	{9, "7450580596923828125"}, // * 134217728
774}
775
776// Is the leading prefix of b lexicographically less than s?
777func prefixIsLessThan(b []byte, s string) bool {
778	for i := 0; i < len(s); i++ {
779		if i >= len(b) {
780			return true
781		}
782		if b[i] != s[i] {
783			return b[i] < s[i]
784		}
785	}
786	return false
787}
788
789// Binary shift left (/ 2) by k bits.  k <= maxShift to avoid overflow.
790func leftShift(a *decimal, k uint) {
791	delta := leftcheats[k].delta
792	if prefixIsLessThan(a.d[0:a.nd], leftcheats[k].cutoff) {
793		delta--
794	}
795
796	r := a.nd         // read index
797	w := a.nd + delta // write index
798	n := 0
799
800	// Pick up a digit, put down a digit.
801	for r--; r >= 0; r-- {
802		n += (int(a.d[r]) - '0') << k
803		quo := n / 10
804		rem := n - 10*quo
805		w--
806		if w < len(a.d) {
807			a.d[w] = byte(rem + '0')
808		} else if rem != 0 {
809			a.trunc = true
810		}
811		n = quo
812	}
813
814	// Put down extra digits.
815	for n > 0 {
816		quo := n / 10
817		rem := n - 10*quo
818		w--
819		if w < len(a.d) {
820			a.d[w] = byte(rem + '0')
821		} else if rem != 0 {
822			a.trunc = true
823		}
824		n = quo
825	}
826
827	a.nd += delta
828	if a.nd >= len(a.d) {
829		a.nd = len(a.d)
830	}
831	a.dp += delta
832	trim(a)
833}
834
835// Binary shift left (k > 0) or right (k < 0).
836func (a *decimal) Shift(k int) {
837	switch {
838	case a.nd == 0:
839		// nothing to do: a == 0
840	case k > 0:
841		for k > maxShift {
842			leftShift(a, maxShift)
843			k -= maxShift
844		}
845		leftShift(a, uint(k))
846	case k < 0:
847		for k < -maxShift {
848			rightShift(a, maxShift)
849			k += maxShift
850		}
851		rightShift(a, uint(-k))
852	}
853}
854
855// If we chop a at nd digits, should we round up?
856func shouldRoundUp(a *decimal, nd int) bool {
857	if nd < 0 || nd >= a.nd {
858		return false
859	}
860	if a.d[nd] == '5' && nd+1 == a.nd { // exactly halfway - round to even
861		// if we truncated, a little higher than what's recorded - always round up
862		if a.trunc {
863			return true
864		}
865		return nd > 0 && (a.d[nd-1]-'0')%2 != 0
866	}
867	// not halfway - digit tells all
868	return a.d[nd] >= '5'
869}
870
871// Round a to nd digits (or fewer).
872// If nd is zero, it means we're rounding
873// just to the left of the digits, as in
874// 0.09 -> 0.1.
875func (a *decimal) Round(nd int) {
876	if nd < 0 || nd >= a.nd {
877		return
878	}
879	if shouldRoundUp(a, nd) {
880		a.RoundUp(nd)
881	} else {
882		a.RoundDown(nd)
883	}
884}
885
886// Round a down to nd digits (or fewer).
887func (a *decimal) RoundDown(nd int) {
888	if nd < 0 || nd >= a.nd {
889		return
890	}
891	a.nd = nd
892	trim(a)
893}
894
895// Round a up to nd digits (or fewer).
896func (a *decimal) RoundUp(nd int) {
897	if nd < 0 || nd >= a.nd {
898		return
899	}
900
901	// round up
902	for i := nd - 1; i >= 0; i-- {
903		c := a.d[i]
904		if c < '9' { // can stop after this digit
905			a.d[i]++
906			a.nd = i + 1
907			return
908		}
909	}
910
911	// Number is all 9s.
912	// Change to single 1 with adjusted decimal point.
913	a.d[0] = '1'
914	a.nd = 1
915	a.dp++
916}
917
918// Extract integer part, rounded appropriately.
919// No guarantees about overflow.
920func (a *decimal) RoundedInteger() uint64 {
921	if a.dp > 20 {
922		return 0xFFFFFFFFFFFFFFFF
923	}
924	var i int
925	n := uint64(0)
926	for i = 0; i < a.dp && i < a.nd; i++ {
927		n = n*10 + uint64(a.d[i]-'0')
928	}
929	for ; i < a.dp; i++ {
930		n *= 10
931	}
932	if shouldRoundUp(a, a.dp) {
933		n++
934	}
935	return n
936}
937