Skip to content

Commit a65ef0e

Browse files
dracarys18jhpratt
andauthored
fix: dont round off floats while formatting (#679)
Co-authored-by: Jacob Pratt <jacob@jhpratt.dev>
1 parent 38beb4a commit a65ef0e

File tree

2 files changed

+26
-0
lines changed

2 files changed

+26
-0
lines changed

tests/formatting.rs

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
use std::io;
2+
use std::num::NonZeroU8;
23

34
use time::format_description::well_known::iso8601::{DateKind, OffsetPrecision, TimePrecision};
45
use time::format_description::well_known::{iso8601, Iso8601, Rfc2822, Rfc3339};
@@ -226,6 +227,26 @@ fn iso_8601() -> time::Result<()> {
226227
Ok(())
227228
}
228229

230+
#[test]
231+
fn iso_8601_issue_678() -> time::Result<()> {
232+
macro_rules! assert_format_config {
233+
($formatted:literal $(, $($config:tt)+)?) => {
234+
assert_eq!(
235+
datetime!(2021-01-02 03:04:05.999_999_999 UTC).format(
236+
&Iso8601::<{ iso8601::Config::DEFAULT$($($config)+)?.encode() }>
237+
)?,
238+
$formatted
239+
);
240+
};
241+
}
242+
243+
assert_format_config!("2021-01-02T03:04:05.999999999Z", .set_time_precision(TimePrecision::Second { decimal_digits: NonZeroU8::new(9) }));
244+
assert_format_config!("2021-01-02T03:04:05.999999Z", .set_time_precision(TimePrecision::Second { decimal_digits: NonZeroU8::new(6) }));
245+
assert_format_config!("2021-01-02T03:04:05.999Z", .set_time_precision(TimePrecision::Second { decimal_digits: NonZeroU8::new(3) }));
246+
247+
Ok(())
248+
}
249+
229250
#[test]
230251
fn format_time() -> time::Result<()> {
231252
let format_output = [

time/src/formatting/mod.rs

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
33
pub(crate) mod formattable;
44
mod iso8601;
5+
56
use core::num::NonZeroU8;
67
use std::io;
78

@@ -73,6 +74,10 @@ pub(crate) fn format_float(
7374
) -> io::Result<usize> {
7475
match digits_after_decimal {
7576
Some(digits_after_decimal) => {
77+
// Truncate the decimal points up to the precision
78+
let trunc_num = 10_f64.powi(digits_after_decimal.get().cast_signed().extend());
79+
let value = f64::trunc(value * trunc_num) / trunc_num;
80+
7681
let digits_after_decimal = digits_after_decimal.get().extend();
7782
let width = digits_before_decimal.extend::<usize>() + 1 + digits_after_decimal;
7883
write!(output, "{value:0>width$.digits_after_decimal$}")?;

0 commit comments

Comments
 (0)