rescale returns a rescaled version of the decimal. Returned decimal may be less precise if the given exponent is bigger than the initial exponent of the Decimal. NOTE: this will truncate, NOT round Example: d := New(12345, -4) d2 := d.rescale(-1) d3 := d2.rescale(-4) println(d1) println(d2)
(exp int32)
| 483 | // 1.2 |
| 484 | // 1.2000 |
| 485 | func (d Decimal) rescale(exp int32) Decimal { |
| 486 | d.ensureInitialized() |
| 487 | |
| 488 | if d.exp == exp { |
| 489 | return Decimal{ |
| 490 | new(big.Int).Set(d.value), |
| 491 | d.exp, |
| 492 | } |
| 493 | } |
| 494 | |
| 495 | // NOTE(vadim): must convert exps to float64 before - to prevent overflow |
| 496 | diff := math.Abs(float64(exp) - float64(d.exp)) |
| 497 | value := new(big.Int).Set(d.value) |
| 498 | |
| 499 | expScale := new(big.Int).Exp(tenInt, big.NewInt(int64(diff)), nil) |
| 500 | if exp > d.exp { |
| 501 | value = value.Quo(value, expScale) |
| 502 | } else if exp < d.exp { |
| 503 | value = value.Mul(value, expScale) |
| 504 | } |
| 505 | |
| 506 | return Decimal{ |
| 507 | value: value, |
| 508 | exp: exp, |
| 509 | } |
| 510 | } |
| 511 | |
| 512 | // Abs returns the absolute value of the decimal. |
| 513 | func (d Decimal) Abs() Decimal { |