Append appends to buf the string form of the decimal number d, as generated by d.Text, and returns the extended buffer.
(buf []byte, fmtString byte)
| 43 | // Append appends to buf the string form of the decimal number d, |
| 44 | // as generated by d.Text, and returns the extended buffer. |
| 45 | func (d *Decimal) Append(buf []byte, fmtString byte) []byte { |
| 46 | // sign |
| 47 | if d.Negative { |
| 48 | buf = append(buf, '-') |
| 49 | } |
| 50 | |
| 51 | switch d.Form { |
| 52 | case Finite: |
| 53 | // ignore |
| 54 | case NaN: |
| 55 | return append(buf, "NaN"...) |
| 56 | case NaNSignaling: |
| 57 | return append(buf, "sNaN"...) |
| 58 | case Infinite: |
| 59 | return append(buf, "Infinity"...) |
| 60 | default: |
| 61 | return append(buf, "unknown"...) |
| 62 | } |
| 63 | |
| 64 | var scratch [16]byte |
| 65 | digits := d.Coeff.Append(scratch[:0], 10) |
| 66 | switch fmtString { |
| 67 | case 'e', 'E': |
| 68 | return fmtE(buf, fmtString, d, digits) |
| 69 | case 'f': |
| 70 | return fmtF(buf, d, digits) |
| 71 | case 'g', 'G': |
| 72 | digitLen := len(digits) |
| 73 | // PG formats all 0s after the decimal point in the 0E-<exponent> case |
| 74 | // (e.g. 0E-9 should be 0.000000000). With the `adjExponentLimit` below, |
| 75 | // this does not do that, so for 0 with negative coefficients we pad |
| 76 | // the digit length. |
| 77 | // Ref: https://github.com/cockroachdb/cockroach/issues/102217 |
| 78 | // |
| 79 | // To avoid leaking too much memory for pathological cases, e.g. |
| 80 | // 0E-100000000, we also fall back to the default exponent format |
| 81 | // handling when the exponent is below cockroach's lowest supported 0 |
| 82 | // coefficient. |
| 83 | if d.Coeff.BitLen() == 0 && d.Exponent >= lowestZeroNegativeCoefficientCockroach && d.Exponent < 0 { |
| 84 | digitLen += int(-d.Exponent) |
| 85 | } |
| 86 | // See: http://speleotrove.com/decimal/daconvs.html#reftostr |
| 87 | const adjExponentLimit = -6 |
| 88 | adj := int(d.Exponent) + (digitLen - 1) |
| 89 | if d.Exponent <= 0 && adj >= adjExponentLimit { |
| 90 | return fmtF(buf, d, digits) |
| 91 | } |
| 92 | // We need to convert the either g or G into a e or E since that's what fmtE |
| 93 | // expects. This is indeed fmtString - 2, but attempting to do that in a way that |
| 94 | // illustrates the intention. |
| 95 | return fmtE(buf, fmtString+'e'-'g', d, digits) |
| 96 | } |
| 97 | |
| 98 | if d.Negative { |
| 99 | buf = buf[:len(buf)-1] // sign was added prematurely - remove it again |
| 100 | } |
| 101 | return append(buf, '%', fmtString) |
| 102 | } |