Skip to main content

Decimal

Struct Decimal 

Source
pub struct Decimal { /* private fields */ }
Expand description

An exact base-10 decimal: mantissa × 10⁻ˢᶜᵃˡᵉ.

This is what every OCPP number is carried in. The schemas say "type": "number" and the obvious reading of that is f64; it is the wrong one, for three reasons that all cost money:

  • Resolution is a claim. A meter reporting 2935.600 kWh is stating three decimals of accuracy. As an f64, 2935.600 and 2935.6 are the same value and the claim is gone. A Decimal keeps the scale the station sent, so the value decodes, prints and re-encodes as 2935.600. OCMF says the same of its own readings: the representation “must not be transformed … thus potentially the number of valid digits” (Tab. 7, RV).
  • Energy is a subtraction. OCPP defines a session’s energy as the difference of two register readings, and in f64 10.1 - 0.1 is 10.000000000000002.
  • The 2.1 Tariff and Cost block is money.
use ocpp_kit::decimal;
use ocpp_kit::types::Decimal;

let register: Decimal = "2935.600".parse().unwrap();
assert_eq!(register.scale(), 3);
assert_eq!(register.to_string(), "2935.600");

// The difference OCPP defines a session's energy as, exactly.
assert_eq!(decimal!(20.2) - decimal!(10.1), decimal!(10.1));

Literals are written with decimal!, which parses the source text at compile time; integers convert with From. There is deliberately no From<f64> — a number that has been through a float has already lost what this type exists to keep — and the conversions that do exist are named to_f64_lossy and from_f64_lossy so a signature says what it costs. Nothing else in this crate calls either, and cargo xtask no-floats fails the build if an f32 or f64 reaches any public signature.

§What exactly is preserved

The fraction digits — the resolution claim — and therefore the positional spelling: 2935.600 in, 2935.600 out; 5 in, 5 out, not 5.0. What is not preserved is a spelling that carries no information a decimal number has: exponent notation is normalized (1.5e3 re-encodes as 1500), as are a leading + and leading zeros. Where the exact bytes are load-bearing — a signed OCMF or EDL record — they are not a JSON number at all, and metering carries those untouched.

§Range

The mantissa is an i64 and the scale is at most MAX_SCALE (18), so a value carries up to 19 significant digits — a register in Wh with three decimals up to 10¹⁵ Wh. Text with more precision than that is rounded half to even by from_ascii; text whose integer part does not fit is refused.

§Equality

PartialEq and Ord compare numerically, so 2.50 == 2.5 — that is what a comparison between two readings should answer, and Hash agrees with it. The scale is still there and still round-trips; eq_exact compares it too when the spelling is what matters.

§Arithmetic

Addition, subtraction and multiplication are exact, at the scale the operands imply, and the operators panic on overflow exactly as the integer ones do; the checked_ forms return None instead. Division has no exact answer in base ten, so checked_div takes the scale to round at rather than guessing one. A change of unit prefix is checked_pow10, which moves the point and so cannot round at all.

§Wire format

Serialize and Deserialize speak serde_json’s raw-value protocol, which is how the source token reaches this type instead of the f64 a JSON parser would otherwise round it to. Any other data format falls back to the ordinary numeric path and is lossy in the way that format is lossy. OCPP-J is JSON, so this is the format that matters.

§Handing the value to another decimal type

A billing platform generally has a decimal type of its own. The conversion is exact in either direction, so this crate depends on none of them:

ⓘ
let exact = rust_decimal::Decimal::new(reading.mantissa(), u32::from(reading.scale()));
let back = ocpp_kit::types::Decimal::new(
    i64::try_from(exact.mantissa()).unwrap(),
    u8::try_from(exact.scale()).unwrap(),
);

Anything that parses decimal text — bigdecimal, a database NUMERIC — takes to_string(), which is the value at its own scale and never in exponent form.

Implementations§

Source§

impl Decimal

Source

pub const ZERO: Self

Zero, at scale 0.

Source

pub const ONE: Self

One, at scale 0.

Source

pub const MAX_SCALE: u8 = 18

The largest scale a Decimal can carry.

Source

pub const fn new(mantissa: i64, scale: u8) -> Self

mantissa × 10⁻ˢᶜᵃˡᵉ.

§Panics

If scale exceeds MAX_SCALE. Use try_new when the scale is not known at compile time.

Source

pub const fn try_new(mantissa: i64, scale: u8) -> Option<Self>

mantissa × 10⁻ˢᶜᵃˡᵉ, or None when scale exceeds MAX_SCALE.

Source

pub const fn from_i64(value: i64) -> Self

A whole number.

Source

pub const fn mantissa(self) -> i64

The mantissa: the value with the decimal point removed.

Source

pub const fn scale(self) -> u8

How many digits follow the decimal point.

This is the resolution the value was written with, and it is preserved: a station that sent 2935.600 gets 3 here, and 2935.600 back on the wire.

Source

pub const fn is_zero(self) -> bool

Whether the value is zero, whatever its scale.

Source

pub const fn signum(self) -> i32

-1, 0 or 1.

Source

pub const fn eq_exact(self, other: Self) -> bool

Whether two values have both the same number and the same scale — 2.50 and 2.5 are equal but not identical.

Source

pub const fn normalized(self) -> Self

The same number with every trailing zero removed: 2.500 becomes 2.5.

Source

pub const fn rescale(self, scale: u8) -> Option<Self>

The same number written at scale, or None when that would lose a digit or overflow.

Exact by construction: it never rounds. Use round_to to round.

Source

pub const fn round_to(self, scale: u8) -> Option<Self>

The value rounded to scale, half to even, or None on overflow or an out-of-range scale.

Source

pub const fn checked_add(self, rhs: Self) -> Option<Self>

The sum, at the larger of the two scales, or None on overflow.

Source

pub const fn checked_sub(self, rhs: Self) -> Option<Self>

The difference, at the larger of the two scales, or None on overflow.

This is the operation OCPP defines a session’s energy as, and the reason this type exists: 20.2 - 10.1 is 10.1, not 10.100000000000001.

Source

pub const fn checked_mul(self, rhs: Self) -> Option<Self>

The product, at the sum of the two scales, or None when that does not fit.

Source

pub const fn checked_div(self, rhs: Self, scale: u8) -> Option<Self>

The quotient at scale, rounded half to even, or None when rhs is zero or the result does not fit.

Division is the one operation that has no exact answer in base ten — 1 / 3 does not terminate — so the scale to round at is a parameter rather than a guess.

Source

pub const fn checked_pow10(self, exp: i32) -> Option<Self>

The value multiplied by 10^exp, exactly, or None when it does not fit.

A shift of the decimal point, which is all a change of unit prefix is: kWh to Wh is pow10(3), and the 2.x unitOfMeasure.multiplier is exactly this operation. Unlike a multiplication by a literal 1000.0 it cannot introduce a rounding error, because it only moves the point.

Source

pub const fn checked_abs(self) -> Option<Self>

The absolute value, or None for a mantissa of i64::MIN.

Source

pub const fn checked_neg(self) -> Option<Self>

The negation, or None for a mantissa of i64::MIN.

Source

pub const fn min(self, other: Self) -> Self

The smaller of two values.

Source

pub const fn max(self, other: Self) -> Self

The larger of two values.

Source

pub const fn compare(self, other: Self) -> Ordering

Numeric comparison, in a const context.

Source

pub const fn from_ascii(bytes: &[u8]) -> Result<Self, ParseDecimalError>

Parses a decimal from ASCII, exactly.

Accepts everything JSON’s number production allows — an optional sign, digits, an optional fraction, an optional e/E exponent — plus a leading +, leading zeros and surrounding whitespace, none of which JSON permits but stations send anyway. The scale of the result is the number of fraction digits written, so 2935.600 parses to scale 3 and prints back identically.

§Errors

ParseDecimalError::Invalid when the text is not a number at all, and ParseDecimalError::Overflow when its integer part needs more than 19 digits. Excess fraction digits are rounded half to even rather than refused, because refusing a value the schema calls valid is worse than rounding at the nineteenth significant digit.

Source

pub const fn from_literal(text: &str) -> Self

Parses a Rust numeric literal, panicking instead of returning an error.

This is what decimal! expands to, so the panic is a compile error rather than a runtime one. It differs from from_ascii in accepting Rust’s _ digit separators — decimal!(11_000) is how the number would be written anywhere else in the source, and JSON never contains one, so the leniency costs the wire path nothing.

§Panics

If the text is not a decimal number.

Source

pub fn to_f64_lossy(self) -> f64

The value as an f64, correctly rounded.

Named for what it costs: past 15 significant digits the result is not the number this Decimal holds, and no arithmetic done on it afterwards is exact. Nothing in this crate calls it.

Source

pub fn from_f64_lossy(value: f64) -> Option<Self>

The decimal an f64 is nearest to, or None for an infinity, a NaN, or a magnitude out of range.

Named for what it costs: the f64 0.1 is not one tenth, and this returns the shortest decimal that reads back as the same f64 — 0.1 — rather than the value it actually holds. That is the friendly answer, and it is still a guess about what the number was before it became a float. Parse the text instead when there is text.

Trait Implementations§

Source§

impl Add for Decimal

Source§

fn add(self, rhs: Decimal) -> Decimal

§Panics

On overflow, like the integer operators. Use the checked_ form to handle it.

Source§

type Output = Decimal

The resulting type after applying the + operator.
Source§

impl AddAssign for Decimal

Source§

fn add_assign(&mut self, rhs: Decimal)

Performs the += operation. Read more
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 Copy for Decimal

Source§

impl Debug for Decimal

Source§

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

The number, not its representation: Decimal(2935.600). A {mantissa, scale} dump is what a reader has to decode by hand every time one of these appears in a log line.

Source§

impl Default for Decimal

Source§

fn default() -> Decimal

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

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

Source§

fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error>

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

impl Display for Decimal

Source§

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

Writes the value at its own scale, so 2935.600 prints as 2935.600.

Source§

impl Div for Decimal

Source§

fn div(self, rhs: Decimal) -> Decimal

Division at Decimal::MAX_SCALE, rounded half to even.

§Panics

On division by zero or overflow. Decimal::checked_div takes the scale to round at and returns None instead, which is what production code should use.

Source§

type Output = Decimal

The resulting type after applying the / operator.
Source§

impl Eq for Decimal

Source§

impl From<i8> for Decimal

Source§

fn from(value: i8) -> Self

Converts to this type from the input type.
Source§

impl From<i16> for Decimal

Source§

fn from(value: i16) -> Self

Converts to this type from the input type.
Source§

impl From<i32> for Decimal

Source§

fn from(value: i32) -> Self

Converts to this type from the input type.
Source§

impl From<i64> for Decimal

Source§

fn from(value: i64) -> Self

Converts to this type from the input type.
Source§

impl From<u8> for Decimal

Source§

fn from(value: u8) -> Self

Converts to this type from the input type.
Source§

impl From<u16> for Decimal

Source§

fn from(value: u16) -> Self

Converts to this type from the input type.
Source§

impl From<u32> for Decimal

Source§

fn from(value: u32) -> Self

Converts to this type from the input type.
Source§

impl FromStr for Decimal

Source§

type Err = ParseDecimalError

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

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

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

impl Hash for Decimal

Source§

fn hash<H: Hasher>(&self, state: &mut H)

Hashes the normalized value, so 2.50 and 2.5 — which compare equal — hash equal.

1.3.0 · Source§

fn hash_slice<H>(data: &[Self], state: &mut H)
where H: Hasher, Self: Sized,

Feeds a slice of this type into the given Hasher. Read more
Source§

impl Mul for Decimal

Source§

fn mul(self, rhs: Decimal) -> Decimal

§Panics

On overflow, like the integer operators. Use the checked_ form to handle it.

Source§

type Output = Decimal

The resulting type after applying the * operator.
Source§

impl Neg for Decimal

Source§

fn neg(self) -> Decimal

§Panics

Only for a mantissa of i64::MIN, which no parsed value has.

Source§

type Output = Decimal

The resulting type after applying the - operator.
Source§

impl Ord for Decimal

Source§

fn cmp(&self, other: &Self) -> Ordering

This method returns an Ordering between self and other. Read more
1.21.0 (const: unstable) · Source§

fn max(self, other: Self) -> Self
where Self: Sized,

Compares and returns the maximum of two values. Read more
1.21.0 (const: unstable) · Source§

fn min(self, other: Self) -> Self
where Self: Sized,

Compares and returns the minimum of two values. Read more
1.50.0 (const: unstable) · Source§

fn clamp(self, min: Self, max: Self) -> Self
where Self: Sized,

Restrict a value to a certain interval. Read more
Source§

fn clamp_to<R>(self, range: R) -> Self
where Self: Sized, R: ClampBounds<Self>,

🔬This is a nightly-only experimental API. (clamp_to)
Restrict a value to a certain range. Read more
Source§

impl PartialEq for Decimal

Source§

fn eq(&self, other: &Self) -> 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

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: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error>

Writes the number as the peer would have written it: the mantissa at its own scale, so 2935.600 goes back out as 2935.600 and not as 2935.6.

Source§

impl Sub for Decimal

Source§

fn sub(self, rhs: Decimal) -> Decimal

§Panics

On overflow, like the integer operators. Use the checked_ form to handle it.

Source§

type Output = Decimal

The resulting type after applying the - operator.
Source§

impl SubAssign for Decimal

Source§

fn sub_assign(&mut self, rhs: Decimal)

Performs the -= operation. Read more
Source§

impl Sum for Decimal

Source§

fn sum<I: Iterator<Item = Decimal>>(iter: I) -> Decimal

Takes an iterator and generates Self from the elements by “summing up” the items.
Source§

impl TryFrom<Decimal> for i64

Source§

fn try_from(value: Decimal) -> Result<Self, Self::Error>

Succeeds only when the value is a whole number.

Source§

type Error = ParseDecimalError

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

impl TryFrom<u64> for Decimal

Source§

type Error = ParseDecimalError

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

fn try_from(value: u64) -> Result<Self, Self::Error>

Performs the conversion.
Source§

impl Validate for Decimal

Source§

fn validate_at(&self, _path: &mut ValidationPath, _out: &mut Violations)

Nothing to check: unlike an f64, a Decimal cannot hold a value JSON has no spelling for. Range constraints are emitted per field by the code generator.

Source§

fn validate(&self) -> Result<(), Violations>

Validates this value from the payload root.

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 = !

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.