Skip to content

DecimalAmount

DecimalAmount (Virtufin.Core.Position) is an exact base-10 fixed-point number whose precision (number of fractional digits) is part of the value. It is the decimal type of every Virtufin payload schema; its wire form and its Python and TypeScript twins are below.

The struct

public readonly record struct DecimalAmount(long Whole, ulong Fraction, int N);
  • The value is Whole + Fraction / 10^N.
  • Fraction is always a magnitude in [0, 10^N). For a negative value, Whole is rounded down: −0.5 at precision 1 is Whole = -1, Fraction = 5.
  • N is 0 to MaxPrecision (18), because 10^18 is the largest power of ten a long holds.
  • The cardinal is the value as one integer, value × 10^N (ToCardinal()); the amount is the pair (cardinal, precision).

Building one

Method Gives
DecimalAmount.Parse("0.00100") the exact value of the text, at as many decimals as it has (0.00100 at precision 5). Text is -?digits[.digits], invariant, without an exponent; anything else throws FormatException (TryParse returns false).
DecimalAmount.From(1.005m, 2) a decimal at the given precision, a tie rounded away from zero (1.01)
DecimalAmount.OfCardinal(4200050, 2) the amount cardinal / 10^n (42000.50)
DecimalAmount.FromWire(wire) the amount a virtufin.core.DecimalAmount message carries

Reading it back: ToCardinal(), ToCardinal(n) (rescaled, a tie rounded away from zero), ToDecimal(), ToWire(), and ToString(), which gives exactly N decimals (-0.50, 42000).

Arithmetic

All arithmetic is checked and throws OverflowException on overflow.

Operation Precision of the result
a + b, a - b the operands' precision; differing precisions throw PrecisionMismatchException
a * b the sum of the operands' precisions (exact in base 10)
a / b the dividend's precision, a tie rounded away from zero; a zero divisor throws DivideByZeroException
var a = DecimalAmount.Parse("10.50");
var b = DecimalAmount.Parse("3.25");

var sum = a + b;    // 13.75   (precision 2)
var prod = a * b;   // 34.1250 (precision 4)
var quot = a / b;   // 3.23    (precision 2)
a + DecimalAmount.Parse("1.0");   // throws PrecisionMismatchException

Subtraction may give a negative value; whether that makes sense is the caller's decision (it does for cash flows, not for inventory).

One precision without losing a digit

Amounts often arrive at their source's own precision (a venue writes 42000.5 and 42000.55), and +/- need one precision. AtPrecision(n) gives the same value at n decimals and never rounds: it throws InvalidOperationException when a non-zero digit would be lost, and OverflowException when the value does not fit. Bring each amount to your working precision before you add it to others:

var close = DecimalAmount.Parse("42000.5").AtPrecision(8);   // 42000.50000000
DecimalAmount.Parse("0.123456789").AtPrecision(8);           // throws: it would be rounded

From(value, n) and ToCardinal(n) are the rounding conversions, for when a rounding is what you want.

Equality and ordering

Two amounts are equal only when their value and their precision match: 1.0 (precision 1) and 1.00 (precision 2) are different values, because a precision carries meaning ("I quoted you 1.0" is not "I quoted you 1.00").

Equality and ordering report a precision mismatch differently, and deliberately so. A different N is, in effect, a different type. C# cannot express that, so the check happens at run time. The platform follows the split the BCL uses for an actual type mismatch: object.Equals returns false, while IComparable.CompareTo throws.

one1.Equals(one2);    // false
one1 == one2;         // false
one1.CompareTo(one2); // throws PrecisionMismatchException
one1 + one2;          // throws PrecisionMismatchException: arithmetic needs a decision, comparison does not

Equality has to stay total: dictionaries, Contains, Distinct, and the generated equality of any record holding a DecimalAmount all call it where an exception could not be caught.

With a unit

  • DecimalQuantity<U>(DecimalAmount Amount, U Unit) pairs an amount with an IUnit (an asset or a currency).
  • Cash (Virtufin.Base) pairs an amount with a Currency. It has no arithmetic operators yet; mixing currencies is meant to be rejected, never converted silently.

Wire form

Every payload schema carries a decimal as virtufin.core.DecimalAmount (proto/virtufin/core/decimal.proto, generated into Virtufin.Core.Wire):

message DecimalAmount { sint64 cardinal = 1; uint32 precision = 2; }
message DecimalQuantity { DecimalAmount amount = 1; string unit = 2; }
  • The FlatBuffers twin is schemas/decimal.fbs.
  • Both files ship in the Virtufin.Core package (proto/, schemas/), so devkits can compile schemas that import them.
  • A message whose values share one precision may carry the precision once and the values as bare cardinals, as the order-book image does.
  • No payload carries money, prices or quantities as floating point or as text.

Python and TypeScript

Language Package Type
Python virtufin-core (virtufin.core.DecimalAmount) cardinal: int, precision: int; parse, from_decimal, at_precision, to_decimal() (a decimal.Decimal), to_wire/from_wire
TypeScript @virtufin/core (DecimalAmount) cardinal: bigint, precision: number; parse, fromDecimal (from text), atPrecision, toString(), equals, toWire/fromWire

The shared vectors conformance/decimal-amount.v1.json hold all three languages to the same cardinal, precision, text and wire bytes for every case: parsing, invalid text, rounding, lossless rescaling (at_precision, and the cases it refuses), and protobuf encoding.

Performance

DecimalAmount is a 24-byte readonly record struct (long, ulong, int, plus padding). It is passed by value without allocation, and equality and arithmetic are O(1). On high-rate paths (market-data ingestion, order-book updates) it is the recommended type; System.Decimal is fine for occasional calculations.

Why not decimal: Design decisions.