Round rounds the decimal to places decimal places. If places < 0, it will round the integer part to the nearest 10^(-places). Example: NewFromFloat(5.45).Round(1).String() // output: "5.5" NewFromFloat(545).Round(-1).String() // output: "550"
(places int32)
| 1521 | // NewFromFloat(5.45).Round(1).String() // output: "5.5" |
| 1522 | // NewFromFloat(545).Round(-1).String() // output: "550" |
| 1523 | func (d Decimal) Round(places int32) Decimal { |
| 1524 | if d.exp == -places { |
| 1525 | return d |
| 1526 | } |
| 1527 | // truncate to places + 1 |
| 1528 | ret := d.rescale(-places - 1) |
| 1529 | |
| 1530 | // add sign(d) * 0.5 |
| 1531 | if ret.value.Sign() < 0 { |
| 1532 | ret.value.Sub(ret.value, fiveInt) |
| 1533 | } else { |
| 1534 | ret.value.Add(ret.value, fiveInt) |
| 1535 | } |
| 1536 | |
| 1537 | // floor for positive numbers, ceil for negative numbers |
| 1538 | _, m := ret.value.DivMod(ret.value, tenInt, new(big.Int)) |
| 1539 | ret.exp++ |
| 1540 | if ret.value.Sign() < 0 && m.Cmp(zeroInt) != 0 { |
| 1541 | ret.value.Add(ret.value, oneInt) |
| 1542 | } |
| 1543 | |
| 1544 | return ret |
| 1545 | } |
| 1546 | |
| 1547 | // RoundCeil rounds the decimal towards +infinity. |
| 1548 | // |