Skip to content

Commit

Permalink
handle minimum_integer_digits and maximum_significant_digits
Browse files Browse the repository at this point in the history
  • Loading branch information
JasperDeSutter committed Dec 15, 2022
1 parent b2301d3 commit 753f77b
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 4 deletions.
12 changes: 10 additions & 2 deletions fluent-bundle/src/types/number.rs
Original file line number Diff line number Diff line change
Expand Up @@ -167,12 +167,20 @@ impl FluentNumber {
}

fn as_fixed_decimal(&self) -> FixedDecimal {
let mut fixed_decimal =
FixedDecimal::try_from_f64(self.value, DoublePrecision::Floating).unwrap();
let precision = if let Some(maxsd) = self.options.maximum_significant_digits {
DoublePrecision::SignificantDigits(maxsd as u8)
} else {
DoublePrecision::Floating
};

let mut fixed_decimal = FixedDecimal::try_from_f64(self.value, precision).unwrap();

if let Some(minfd) = self.options.minimum_fraction_digits {
fixed_decimal.pad_end(-(minfd as i16));
}
if let Some(minid) = self.options.minimum_integer_digits {
fixed_decimal.pad_start(minid as i16);
}
fixed_decimal
}

Expand Down
22 changes: 20 additions & 2 deletions fluent-bundle/tests/types_test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -126,16 +126,34 @@ fn fluent_number_style() {
let num = FluentNumber::new(0.2, FluentNumberOptions::default());
assert_eq!(num.as_string_basic(), "0.2");

let opts = FluentNumberOptions {
let mut opts = FluentNumberOptions {
minimum_fraction_digits: Some(3),
..Default::default()
};

let num = FluentNumber::new(0.2, opts.clone());
assert_eq!(num.as_string_basic(), "0.200");

let num = FluentNumber::new(2.0, opts);
let num = FluentNumber::new(2.0, opts.clone());
assert_eq!(num.as_string_basic(), "2.000");

opts.minimum_integer_digits = Some(3);
opts.minimum_fraction_digits = None;

let num = FluentNumber::new(2.0, opts.clone());
assert_eq!(num.as_string_basic(), "002");

let num = FluentNumber::new(0.2, opts.clone());
assert_eq!(num.as_string_basic(), "000.2");

opts.minimum_integer_digits = None;
opts.maximum_significant_digits = Some(4);

let num = FluentNumber::new(12345.0, opts.clone());
assert_eq!(num.as_string_basic(), "12340");

let num = FluentNumber::new(1.2345, opts);
assert_eq!(num.as_string_basic(), "1.234");
}

#[test]
Expand Down

0 comments on commit 753f77b

Please sign in to comment.