Skip to content

Truncate should parse negative values too, or return error #406

@AlexandrosKyriakakis

Description

@AlexandrosKyriakakis

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:

decimal/decimal.go

Lines 1755 to 1769 in 08afb35

// Truncate truncates off digits from the number, without rounding.
//
// NOTE: precision is the last digit that will not be truncated (must be >= 0).
//
// Example:
//
// decimal.NewFromString("123.456").Truncate(2).String() // "123.45"
func (d Decimal) Truncate(precision int32) Decimal {
d.ensureInitialized()
if precision >= 0 && -precision > d.exp {
return d.rescale(-precision)
}
return d
}

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?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions