Class Percentage
- Namespace
- Trellis.Primitives
- Assembly
- Trellis.Primitives.dll
Represents a percentage value object (value between 0 and 100 inclusive). Ensures that percentage values are within the valid range for percentage calculations.
[JsonConverter(typeof(ParsableJsonConverter<Percentage>))]
public class Percentage : ScalarValueObject<Percentage, decimal>, IComparable<ValueObject>, IComparable, IEquatable<ValueObject>, IConvertible, IFormattable, IFormattableScalarValue<Percentage, decimal>, IScalarValue<Percentage, decimal>, IParsable<Percentage>
- Inheritance
-
Percentage
- Implements
- Inherited Members
- Extension Methods
Examples
Basic usage:
var discount = Percentage.TryCreate(15.5m);
// Returns: Success(Percentage(15.5))
var full = Percentage.TryCreate(100m);
// Returns: Success(Percentage(100))
var zero = Percentage.TryCreate(0m);
// Returns: Success(Percentage(0))
var invalidHigh = Percentage.TryCreate(150m);
// Returns: Failure(Error.InvalidInput with detail "Percentage must be between 0 and 100.")
var invalidNegative = Percentage.TryCreate(-5m);
// Returns: Failure(Error.InvalidInput with detail "Percentage must be between 0 and 100.")
Using helper methods:
var percentage = Percentage.Create(20m);
var amount = 100m;
// Convert to fraction (0.2)
var fraction = percentage.AsFraction();
// Calculate percentage of a value
var result = percentage.Of(amount); // Returns 20m
Remarks
Percentage is a domain primitive that encapsulates percentage validation and provides:
- Validation ensuring value is between 0 and 100 inclusive
- Type safety preventing mixing of percentages with other decimals
- Immutability ensuring values cannot be changed after creation
- IParsable implementation for .NET parsing conventions
- JSON serialization support for APIs and persistence
- Activity tracing for monitoring and diagnostics
- Helper methods for percentage calculations
Common use cases:
- Discount percentages
- Tax rates
- Commission rates
- Progress indicators
- Interest rates
- Any value representing a percentage
Properties
Full
Gets a Percentage representing 100%.
public static Percentage Full { get; }
Property Value
Zero
Gets a Percentage representing 0%.
public static Percentage Zero { get; }
Property Value
Methods
AsFraction()
Returns the percentage as a fraction (0.0 to 1.0).
public decimal AsFraction()
Returns
- decimal
The percentage value divided by 100.
FromFraction(decimal, string?)
Creates a Percentage from a fraction (0.0 to 1.0).
If fieldName is not provided, validation errors use "fraction" as the field name.
public static Result<Percentage> FromFraction(decimal fraction, string? fieldName = null)
Parameters
fractiondecimalThe fraction value (0.0 to 1.0).
fieldNamestringOptional field name for validation error messages. If not provided, defaults to "fraction".
Returns
- Result<Percentage>
Success with the Percentage; otherwise Failure with Error.InvalidInput.
Of(decimal)
Calculates this percentage of the specified amount.
public decimal Of(decimal amount)
Parameters
amountdecimalThe amount to calculate the percentage of.
Returns
- decimal
The percentage of the amount.
Parse(string?, IFormatProvider?)
Parses the string representation of a decimal to its Percentage equivalent.
public static Percentage Parse(string? s, IFormatProvider? provider)
Parameters
sstringproviderIFormatProvider
Returns
ToString()
Returns a string representation of the percentage with a % suffix.
public override string ToString()
Returns
Remarks
The numeric part is formatted with InvariantCulture because this is the wire format Parse(string?, IFormatProvider?) reads back with the invariant culture.
TryCreate(decimal, string?)
Attempts to create a Percentage from the specified decimal.
If fieldName is not provided, validation errors use "percentage" as the field name.
public static Result<Percentage> TryCreate(decimal value, string? fieldName = null)
Parameters
valuedecimalThe decimal value to validate (0-100).
fieldNamestringOptional field name for validation error messages. If not provided, defaults to "percentage".
Returns
- Result<Percentage>
Success with the Percentage if the value is between 0 and 100; otherwise Failure with Error.InvalidInput.
TryCreate(decimal?, string?)
Attempts to create a Percentage from the specified nullable decimal.
If fieldName is not provided, validation errors use "percentage" as the field name.
public static Result<Percentage> TryCreate(decimal? value, string? fieldName = null)
Parameters
valuedecimal?The nullable decimal value to validate (0-100).
fieldNamestringOptional field name for validation error messages. If not provided, defaults to "percentage".
Returns
- Result<Percentage>
Success with the Percentage if the value is between 0 and 100; otherwise Failure with Error.InvalidInput.
TryCreate(string?, IFormatProvider?, string?)
Attempts to create a Percentage from a string using the specified format provider.
Strips a trailing % suffix if present before parsing.
If fieldName is not provided, validation errors use "percentage" as the field name.
public static Result<Percentage> TryCreate(string? value, IFormatProvider? provider, string? fieldName = null)
Parameters
valuestringThe string value to parse (must be a valid decimal, optionally with a trailing %).
providerIFormatProviderThe format provider for culture-sensitive parsing. Defaults to InvariantCulture when null.
fieldNamestringOptional field name for validation error messages. If not provided, defaults to "percentage".
Returns
- Result<Percentage>
Success with the Percentage if valid; Failure with Error.InvalidInput otherwise.
TryCreate(string?, string?)
Attempts to create a Percentage from a string representation.
Strips a trailing % suffix if present before parsing.
If fieldName is not provided, validation errors use "percentage" as the field name.
public static Result<Percentage> TryCreate(string? value, string? fieldName = null)
Parameters
valuestringThe string value to parse (must be a valid decimal, optionally with a trailing %).
fieldNamestringOptional field name for validation error messages. If not provided, defaults to "percentage".
Returns
- Result<Percentage>
Success with the Percentage if valid; Failure with Error.InvalidInput otherwise.
Remarks
Delegates to the TryCreate(string?, IFormatProvider?, string?) overload using the invariant culture.
TryParse(string?, IFormatProvider?, out Percentage)
Tries to parse a string into a Percentage.
public static bool TryParse(string? s, IFormatProvider? provider, out Percentage result)
Parameters
sstringproviderIFormatProviderresultPercentage
Returns
Operators
explicit operator Percentage(decimal)
Explicitly converts a decimal to a Percentage.
public static explicit operator Percentage(decimal value)
Parameters
valuedecimal