[API Proposal]: decimal.Canonicalize
Background and motivation
Since decimal class is documented to preserve trailing zeros, it would be nice to have a way to trim them off.
I suggest the name Canonicalize to be in line with INumberBase.IsCanonical
This is useful for example when using npgsql where the zeros are also preserved. Having a way to trim the trailing zeroes would allow developers to not only save some tiny bytes here and there, but also prevent the issue where adding two decimals inside postgres, with max number of digits, would result in too many digits in the result and thus crash.
Currently only found ways to do this by formatting to a string, trimming the zero chars and then parsing again.
Java has a similar method for it's BigDecimal class: https://docs.oracle.com/en/java/javase/22/docs/api/java.base/java/math/BigDecimal.html#stripTrailingZeros()
Rust has canonical methods for the IEEE 754 numbers:
https://docs.rs/dec/latest/dec/struct.Decimal64.html#method.canonical
Postgres has method trim_scale for the numeric data type:
https://www.postgresql.org/docs/current/functions-math.html#FUNCTIONS-MATH-FUNC-TABLE
Ruby has one for the Decimal class:
https://ruby-rdf.github.io/rdf/RDF/Literal/Decimal.html#canonicalize!-instance_method
Python has one (although its a noop since it's always canonical) https://docs.python.org/3/library/decimal.html#decimal.Decimal.canonical
API Proposal
namespace System.Collections.Generic;
public class decimal
{
public static decimal Canonicalize(decimal value);
}
API Usage
// Fancy the value
var withZeros = 42.55000m;
var withoutZeros = decimal.Canonicalize(withZeros); // value is 42.55m
Alternative Designs
No response
Risks
New methods always have the potential to confuse users I guess?
I couldn't figure out the best area label to add to this issue. If you have write-permissions please help me learn by adding exactly one area label.
Having a way to trim the trailing zeroes would allow developers to not only save some tiny bytes here and there
This would only be beneficial if a particular call to the database had a significant number of decimals in it - otherwise, the overhead of the network call itself is going to dominate. If you're passing that many decimals, you should likely be looking at bulk-load utilities.
Also, this implies that you anticipate the driver using string representation to transmit the values, but drivers (usually) don't work that way. First, because formatting as a string has an extra cost, and second because in many cases such a representation is actually larger than a binary representation.
prevent the issue where adding two decimals inside postgres, with max number of digits, would result in too many digits in the result and thus crash
The proper way to handle this is to know/enforce rounding to a certain number of decimal places, not simply trimming them off.
Additionally, because C#'s decimal has so many fewer digits, it's unlikely to be the cause of the issue (given PostgreSQL's numeric/decimal allow thousands of digits on both sides of the decimal place) ... unless it's digits coming from PostgreSQL, which this wouldn't solve..
Tagging subscribers to this area: @dotnet/area-system-numerics See info in area-owners.md if you want to be subscribed.
Issue Details
Background and motivation
Since decimal class is documented to preserve trailing zeros, it would be nice to have a way to trim them off.
This is useful for example when using npgsql where the zeros are also preserved. Having a way to trim the trailing zeroes would allow developers to not only save some tiny bytes here and there, but also prevent the issue where adding two decimals inside postgres, with max number of digits, would result in too many digits in the result and thus crash.
Currently only found ways to do this by formatting to a string, trimming the zero chars and then parsing again.
API Proposal
namespace System.Collections.Generic;
public class decimal
{
public static decimal TrimTrailingFractionalZeros(decimal value);
}
I think this method would be simply return value for NaN, inf etc...
API Usage
// Fancy the value
var withZeros = 42.55000m;
var withoutZeros = decimal.TrimTrailingFractionalZeros(withZeros); // value is 42.55m
Alternative Designs
No response
Risks
New methods always have the potential to confuse users I guess?
| Author: | lilinus |
|---|---|
| Assignees: | - |
| Labels: |
|
| Milestone: | - |
But there is no nice way of normalizing / trimming trailing franctional zeros at the moment. Options I guess are either formatting then parsing, alternatively (as proposed in https://stackoverflow.com/questions/4525854/remove-trailing-zeros/7983330#7983330): x = x / 1.000000000000000000000000000000000m
The corresponding function already exists in postgres as trim_scale.
And the logic for this operations is basically implemented in DecCalc.Unscale.
Updated suggestion to have the method named Canonicalize
Note that my earlier objection isn't necessarily against this proposal per-se, it was just that those stated reasons didn't seem to be a factor in practive.
Another use (for which we use the workaround in production code at my current project), is canonicalizing user input (without rounding, just removing trailnig zeros).
If it's valid for user input to have a certain number of non-zero digits, it's also valid for those digits to be zero. Whatever method you're using to "fix" the non-zero digit case should also work for zero digits.
Whether the digit is a zero or not shouldn't change whether an exception is thrown.
Yes it's valid and calculations work without any exceptions. But what only there is no way to trim them that is desired. Say I have two user inputs x and y and I want to format the product in a text/csv file.
x = 1.234m y = 0m prod = x * y; str = prod.ToString() // This returns "0.000"
What I suggest is a method to use so we can format it to "0".
str = prod.ToString() // This returns "0.000"
This is a formatting problem and should be handled as such, not as something on the number end. The values are not equivalent - in some use cases the extra zeroes are important. (Yes yes, whichever relevant parties can do/not do whichever, but just throwing that out there)
I'm a little surprised that there isn't a formatting option to trim zeroes in the standard numeric format strings. That's a separate proposal, and maybe something we should look at.
I know they are not equivalent (but .Equals returns true). I think that if it has an important meaning whether there are trailing zeros, then it should imply it is also important when there are none. But there is no good method to trim them.
Formatting to string is one case, but saving them (1 vs 1.00) in binary is also different (e.g. to Postgres as in description)
I don't have a good idea how a formatting options for skipping trailing zeroes would be, so I will keep this open for more input.
In the meantime we will solve it by dividing by 1. 000000000000000000000000000000000m.
In SQL, DECIMAL/NUMERIC are fixed-point fields when defined with precision/scale. When they actually get stored in a column in the DB, it's going to set it to whatever size you've created the field at. And in any case the PostgreSQL fields are wider than the C# version, I stated earlier, so it won't cause a problem on PostgreSQL's side.
I found another workaround for formatting it to a string: d.ToString("0.############################")
This proposal is also helpful for hashing purposes.
The built-in GetHashCode already behaves this way, but if you are to use anything else (say, get the binary representation using decimal.GetBits and supply it to an IncrementalHash), you'd want 1.0m and 1.00m to be considered equal, i.e., produce the same bytes. If there were a normalising method, we could use that before getting the bytes.
Checking the original implementation, I see a Decimal.DecCalc.Unscale method (here @45715d1) that does what we want - I think we just need a public wrapper around it that accepts and returns decimals rather than decimal internals.
Added some examples of other languages that has a similar method.
This proposal is also helpful for hashing purposes.
Broadly speaking, probably the better way to handle this is to round or extend to whatever precision is required for the application generally, at which point the hashing would just fall out naturally. It would also then handle values which have extra digits which are nonzero.
Broadly speaking, probably the better way to handle this is to round or extend to whatever precision is required for the application generally, at which point the hashing would just fall out naturally. It would also then handle values which have extra digits which are nonzero.
While I agree that this is the best practice for developing the final application, we can't write a more generic hashing function without a good way to canonicalise a decimal.
If I'm a library author, for example, I can't expect my consumers to always pass me rounded decimals and likewise, my consumers wouldn't expect me to produce different hashes for 1.0 and 1.00.
I think we can use Decimal's own equality and hashing operations as a reference here. Its Equals considers 1.0 and 1.00 equal, and its GetHashCode produces the same hash for 1.0 and 1.00. This is a sensible default I'd like to be able to mimic without DIY'ing existing (but currently non-public) helpers.
Quick search in github shows 270 results when searching for the workaround to divide by 1.000000000000000000000000000000000m suggested: https://github.com/search?q=%22%2F+1.000000000000000000000000000000000m%22&type=code
we have decimal.Truncate method , does it solve this issue ?
> var a = 1.000000000000m;
> a
1.000000000000
> decimal.Truncate(a)
1
>
we have
decimal.Truncatemethod , does it solve this issue ?var a = 1.000000000000m;
a 1.000000000000 decimal.Truncate(a) 1
Returns the integral digits of the specified Decimal; any fractional digits are discarded.
Absolutely not - the request here is to trim only trailing zeroes, and leave non-zero fractional digits alone:
// Outputs 4.5
var n = (4.500m).Canonicalize();