Trait SubsecRound

trait SubsecRound

Extension trait for subsecond rounding or truncation to a maximum number of digits. Rounding can be used to decrease the error variance when serializing/persisting to lower precision. Truncation is the default behavior in Chrono display formatting. Either can be used to guarantee equality (e.g. for testing) when round-tripping through a lower precision format.

Required Methods

fn round_subsecs(self: Self, digits: u16) -> Self

Return a copy rounded to the specified number of subsecond digits. With 9 or more digits, self is returned unmodified. Halfway values are rounded up (away from zero).

Example

# use chrono::{SubsecRound, Timelike, NaiveDate};
let dt = NaiveDate::from_ymd_opt(2018, 1, 11)
    .unwrap()
    .and_hms_milli_opt(12, 0, 0, 154)
    .unwrap()
    .and_utc();
assert_eq!(dt.round_subsecs(2).nanosecond(), 150_000_000);
assert_eq!(dt.round_subsecs(1).nanosecond(), 200_000_000);
fn trunc_subsecs(self: Self, digits: u16) -> Self

Return a copy truncated to the specified number of subsecond digits. With 9 or more digits, self is returned unmodified.

Example

# use chrono::{SubsecRound, Timelike, NaiveDate};
let dt = NaiveDate::from_ymd_opt(2018, 1, 11)
    .unwrap()
    .and_hms_milli_opt(12, 0, 0, 154)
    .unwrap()
    .and_utc();
assert_eq!(dt.trunc_subsecs(2).nanosecond(), 150_000_000);
assert_eq!(dt.trunc_subsecs(1).nanosecond(), 100_000_000);

Implementors