API reference@evolu/commonType › DecimalString

const DecimalString: brand(
  "DecimalString",
  String,
  (value) =>
    /^(?:0|-?(?:[1-9]\d*|(?:0|[1-9]\d*)\.\d*[1-9]))$/u.test(value)
      ? ok()
      : err<DecimalStringError>({ type: "DecimalString", value }),
  (error) =>
    `The value ${safelyStringifyUnknownValue(error.value)} must be a canonical decimal string.`,
);

Defined in: packages/common/src/Type.ts:6962

Canonical string representation of a signed base-10 decimal value.

Use this Type when a decimal value must remain exact instead of being converted to an IEEE-754 number. Equivalent values have one accepted representation, so leading zeroes, trailing fractional zeroes, -0, plus signs, and exponent notation are rejected.

The decoded value remains a string. Arithmetic requires an explicit decimal or fixed-point representation.

TypeScript template literal types can describe a fixed number of digit positions, but not the arbitrarily long integer and fractional parts accepted here. DecimalString therefore uses a Brand so its TypeScript type does not accept strings that have not been validated.

Use these predefined Types or their corresponding factories to add sign constraints to compatible decimal string Types:

Example

import {
  assertEqual,
  assertErr,
  assertOk,
  assertType,
  Data,
  DecimalString,
} from "@evolu/common";

assertOk(DecimalString.fromUnknown("-10.25"), "-10.25");
assertOk(DecimalString.fromUnknown("0"), "0");
assertOk(DecimalString.fromUnknown("10.25"), "10.25");

const invalid = DecimalString.fromUnknown("10.250");
assertErr(invalid);
assertType(Data, invalid.error);
assertEqual(invalid.error, {
  type: "DecimalString",
  value: "10.250",
});