decimal icon indicating copy to clipboard operation
decimal copied to clipboard

Truncate should parse negative values too, or return error

Open AlexandrosKyriakakis opened this issue 6 months ago • 2 comments

Truncate function would be useful to parse also negative values. So for example,

a := decimal.RequireFromString("5432")
b := a.Truncate(-2)

So b should return 5000, currently it returns a which is misleading. In my opinion it should either return 5000 or an error.

I don't see any reason having this check precision >= 0 here: https://github.com/shopspring/decimal/blob/08afb35517362df21914209a026f65bb33275fbc/decimal.go#L1755-L1769

func (d Decimal) Truncate(precision int32) Decimal {
	d.ensureInitialized()
	if precision >= 0 && -precision > d.exp {
		return d.rescale(-precision)
	}
	return d
}

Since it would work, right out of the box.

Any thoughts or concerns?

AlexandrosKyriakakis avatar Jul 07 '25 10:07 AlexandrosKyriakakis

fyi. some of Round functions support negative value for places parameter. https://github.com/shopspring/decimal/blob/08afb35517362df21914209a026f65bb33275fbc/decimal.go#L1523-L1524

hiohiohio avatar Jul 09 '25 05:07 hiohiohio

cc @mwoss

AlexandrosKyriakakis avatar Jul 15 '25 11:07 AlexandrosKyriakakis