Reduce sets d to x with all trailing zeros removed and returns d and the number of zeros removed.
(x *Decimal)
| 704 | // Reduce sets d to x with all trailing zeros removed and returns d and the |
| 705 | // number of zeros removed. |
| 706 | func (d *Decimal) Reduce(x *Decimal) (*Decimal, int) { |
| 707 | if x.Form != Finite { |
| 708 | d.Set(x) |
| 709 | return d, 0 |
| 710 | } |
| 711 | var nd int |
| 712 | neg := false |
| 713 | switch x.Sign() { |
| 714 | case 0: |
| 715 | nd = int(d.NumDigits()) |
| 716 | d.SetInt64(0) |
| 717 | return d, nd - 1 |
| 718 | case -1: |
| 719 | neg = true |
| 720 | } |
| 721 | d.Set(x) |
| 722 | |
| 723 | // Use a uint64 for the division if possible. |
| 724 | if d.Coeff.IsUint64() { |
| 725 | i := d.Coeff.Uint64() |
| 726 | for i >= 10000 && i%10000 == 0 { |
| 727 | i /= 10000 |
| 728 | nd += 4 |
| 729 | } |
| 730 | for i%10 == 0 { |
| 731 | i /= 10 |
| 732 | nd++ |
| 733 | } |
| 734 | if nd != 0 { |
| 735 | d.Exponent += int32(nd) |
| 736 | d.Coeff.SetUint64(i) |
| 737 | d.Negative = neg |
| 738 | } |
| 739 | return d, nd |
| 740 | } |
| 741 | |
| 742 | // Divide by 10 in a loop. In benchmarks of reduce0.decTest, this is 20% |
| 743 | // faster than converting to a string and trimming the 0s from the end. |
| 744 | var z, r BigInt |
| 745 | d.setBig(&z) |
| 746 | for { |
| 747 | z.QuoRem(&d.Coeff, bigTen, &r) |
| 748 | if r.Sign() == 0 { |
| 749 | d.Coeff.Set(&z) |
| 750 | nd++ |
| 751 | } else { |
| 752 | break |
| 753 | } |
| 754 | } |
| 755 | d.Exponent += int32(nd) |
| 756 | return d, nd |
| 757 | } |
| 758 | |
| 759 | const decimalSize = unsafe.Sizeof(Decimal{}) |
| 760 |