Skip to main content

Decimal

Struct Decimal 

Source
pub struct Decimal(/* private fields */);
Expand description

A rational number with implicit precision, used to represent measurement values and other quantities where the number of significant digits carries meaning.

§Precision is data

FHIR states that the precision of a decimal has significance: a laboratory result of 0.50 mmol/L claims two significant figures where 0.5 claims one, and a dose of 1.000 mg is a different assertion from 1.0 mg. This type therefore stores the lexical form it was given and emits it back unchanged (spec R2.2).

Backed by f64 — which is what serde_json::Number is by default — 0.50 becomes 0.5, 1.000 becomes 1.0, and 12345678901234567890.5 becomes 1.2345678901234567e+19. This crate therefore enables serde_json/arbitrary_precision unconditionally, so a Number carries the lexeme it was parsed from. Cargo features are additive and cannot be switched off by a dependent, which makes precision a guarantee rather than a default someone can lose.

The cost is real and worth stating: arbitrary_precision is global to the compiled binary, so every other crate’s serde_json::Number in the same build also becomes lexeme-preserving, and Number arithmetic goes through as_f64(). For a library whose numbers are drug doses and lab results, that is the correct side to err on.

§Equality is lexical, ordering is numeric

Decimal("1.0") != Decimal("1.00"), because the two say different things about precision and must survive a round trip distinctly. They compare equal, because they denote the same quantity:

use fhir::decimal::Decimal;
use std::cmp::Ordering;

let one_dp = Decimal::new("1.0").unwrap();
let two_dp = Decimal::new("1.00").unwrap();
assert_ne!(one_dp, two_dp);
assert_eq!(one_dp.partial_cmp(&two_dp), Some(Ordering::Equal));

§JSON

The lexeme survives every serde path this crate uses — from_str, from_slice, from_reader, from_value, and through the #[serde(flatten)] that choice elements rely on. A serde_json::Value built in the same binary is likewise lexeme-preserving, so json!(0.50) != json!(0.5), and a round-trip test comparing Values can see precision loss rather than silently tolerating it (spec R13.3).

use fhir::decimal::Decimal;

let parsed: Decimal = ::serde_json::from_str("0.50").unwrap();
assert_eq!(parsed.as_str(), "0.50");
assert_eq!(::serde_json::to_string(&parsed).unwrap(), "0.50");

Implementations§

Source§

impl Decimal

Source

pub fn new(lexeme: impl Into<String>) -> Result<Self, DecimalError>

A decimal from its lexical form, checked against the FHIR decimal production -?(0|[1-9][0-9]*)(\.[0-9]+)?([eE][+-]?[0-9]+)?.

§Errors

Returns DecimalError when the text is not a FHIR decimal.

Source

pub fn as_str(&self) -> &str

The stored lexical form, exactly as received.

Source

pub fn as_f64(&self) -> f64

The value as an f64, which is lossy by definition — use it for arithmetic, never for storage or comparison.

Source

pub fn from_json_number(n: &Number) -> Self

A decimal from an already-parsed serde_json::Number, for callers holding a serde_json::Value. Lossless, because this crate guarantees arbitrary_precision.

Source

pub fn as_number(&self) -> &Number

The underlying serde_json::Number, for interoperating with code that speaks serde_json directly.

Trait Implementations§

Source§

impl Clone for Decimal

Source§

fn clone(&self) -> Decimal

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for Decimal

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Default for Decimal

Source§

fn default() -> Self

Returns the “default value” for a type. Read more
Source§

impl<'de> Deserialize<'de> for Decimal

Source§

fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error>
where __D: Deserializer<'de>,

Deserialize this value from the given Serde deserializer. Read more
Source§

impl Display for Decimal

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Eq for Decimal

Source§

impl FromStr for Decimal

Source§

type Err = DecimalError

The associated error which can be returned from parsing.
Source§

fn from_str(s: &str) -> Result<Self, Self::Err>

Parses a string s to return a value of this type. Read more
Source§

impl PartialEq for Decimal

Source§

fn eq(&self, other: &Decimal) -> bool

Equality operator ==. Read more
1.0.0 (const: unstable) · Source§

fn ne(&self, other: &Rhs) -> bool

Inequality operator !=. Read more
Source§

impl PartialOrd for Decimal

Numeric ordering over lexically distinct values: 1.0 and 1.00 are the same quantity even though they are not the same assertion.

Source§

fn partial_cmp(&self, other: &Self) -> Option<Ordering>

This method returns an ordering between self and other values if one exists. Read more
1.0.0 (const: unstable) · Source§

fn lt(&self, other: &Rhs) -> bool

Tests less than (for self and other) and is used by the < operator. Read more
1.0.0 (const: unstable) · Source§

fn le(&self, other: &Rhs) -> bool

Tests less than or equal to (for self and other) and is used by the <= operator. Read more
1.0.0 (const: unstable) · Source§

fn gt(&self, other: &Rhs) -> bool

Tests greater than (for self and other) and is used by the > operator. Read more
1.0.0 (const: unstable) · Source§

fn ge(&self, other: &Rhs) -> bool

Tests greater than or equal to (for self and other) and is used by the >= operator. Read more
Source§

impl Serialize for Decimal

Source§

fn serialize<__S>(&self, __serializer: __S) -> Result<__S::Ok, __S::Error>
where __S: Serializer,

Serialize this value into the given Serde serializer. Read more
Source§

impl StructuralPartialEq for Decimal

Source§

impl Validate for Decimal

Decimal validates its own lexeme (spec R2.6).

One impl for one shared type: were this written per release, compiling two releases together would be a conflicting-impl error.

Source§

fn validate(&self) -> Vec<ValidationIssue>

Return all validation issues; an empty vector means the value is valid.
Source§

fn is_valid(&self) -> bool

Convenience: true when Validate::validate finds no issues.

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> DeserializeOwned for T
where T: for<'de> Deserialize<'de>,

Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T> ToString for T
where T: Display + ?Sized,

Source§

fn to_string(&self) -> String

Converts the given value to a String. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.