Format numbers

This commit is contained in:
Savanni D'Gerinel 2024-02-29 22:59:54 -05:00
parent d95dd4de50
commit a9d29e6518
3 changed files with 39 additions and 8 deletions

2
Cargo.lock generated
View File

@ -1143,6 +1143,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cbc7fdec9d7f6671a3ebb3282c969962aba67c49f6abac5311959b65cafabc10"
dependencies = [
"displaydoc",
"ryu",
"smallvec",
"writeable",
]
@ -2714,6 +2715,7 @@ version = "0.1.0"
dependencies = [
"chrono",
"chrono-tz",
"fixed_decimal",
"fluent-ergonomics",
"icu",
"icu_locid",

View File

@ -8,6 +8,7 @@ edition = "2021"
[dependencies]
chrono = { version = "0.4" }
chrono-tz = { version = "0.8" }
fixed_decimal = { version = "0.5.5", features = [ "ryu" ] }
fluent-ergonomics = { path = "../fluent-ergonomics" }
icu = { version = "1" }
icu_locid = { version = "1" }

View File

@ -1,16 +1,18 @@
use std::ops::Deref;
use chrono::{Datelike, FixedOffset, NaiveDate, TimeZone, Timelike};
use chrono_tz::{OffsetName, Tz};
use chrono::{Datelike, NaiveDate, Timelike};
use chrono_tz::{Tz};
use fixed_decimal::{FixedDecimal};
use icu::{
datetime::options::length,
timezone::{CustomTimeZone, GmtOffset},
decimal::{FixedDecimalFormatter},
};
use icu_locid::{locale, Locale};
use icu_locid::{Locale};
use icu_provider::DataLocale;
use std::str::FromStr;
use sys_locale::get_locale;
pub use fixed_decimal::FloatPrecision;
#[derive(Clone, Debug)]
pub struct L10N {
locale: Locale,
@ -137,8 +139,15 @@ impl L10N {
formatter.format_to_string(&icu_date.to_any()).unwrap()
}
fn format_f64(&self, value: f64) -> String {
unimplemented!()
fn format_f64(&self, value: f64, precision: FloatPrecision) -> String {
let fdf = FixedDecimalFormatter::try_new(
&self.locale.clone().into(),
Default::default()
).expect("locale should be present");
let number = FixedDecimal::try_from_f64(value, precision).unwrap();
fdf.format_to_string(&FixedDecimal::try_from_f64(value, precision).unwrap())
}
}
@ -259,6 +268,25 @@ mod tests {
#[test]
fn it_formats_a_number_according_to_locale() {
unimplemented!()
let mut l10n = ref_l10n();
assert_eq!(
l10n.format_f64(100.4, FloatPrecision::Floating),
"100.4",
);
assert_eq!(
l10n.format_f64(15000.4, FloatPrecision::Floating),
"15,000.4",
);
l10n.set_locale("de-DE".to_owned());
assert_eq!(
l10n.format_f64(100.4, FloatPrecision::Floating),
"100,4",
);
assert_eq!(
l10n.format_f64(15000.4, FloatPrecision::Floating),
"15.000,4",
);
}
}