Browse Source

feat: support scientific notation and decimal separator (#1688)

Kelvin 2 năm trước cách đây
mục cha
commit
c46b09f182

+ 29 - 4
frontend/rust-lib/flowy-grid/src/services/field/type_options/number_type_option/number_type_option.rs

@@ -100,10 +100,27 @@ impl NumberTypeOptionPB {
     pub(crate) fn format_cell_data(&self, s: &str) -> FlowyResult<NumberCellData> {
         match self.format {
             NumberFormat::Num => {
-                let strnum = NUM_REGEX.replace_all(s, "");
-                match Decimal::from_str(&strnum) {
-                    Ok(value, ..) => Ok(NumberCellData::from_decimal(value)),
-                    Err(_) => Ok(NumberCellData::new()),
+                if SCIENTIFIC_NOTATION_REGEX.is_match(s).unwrap() {
+                    match Decimal::from_scientific(&s.to_lowercase()) {
+                        Ok(value, ..) => Ok(NumberCellData::from_decimal(value)),
+                        Err(_) => Ok(NumberCellData::new()),
+                    }
+                } else {
+                    let draw_numer_string = NUM_REGEX.replace_all(s, "");
+                    let strnum = match draw_numer_string.matches(".").count() {
+                        0 | 1 => draw_numer_string.to_string(),
+                        _ => match EXTRACT_NUM_REGEX.captures(&draw_numer_string) {
+                            Ok(captures) => match captures {
+                                Some(capture) => capture[1].to_string(),
+                                None => "".to_string(),
+                            },
+                            Err(_) => "".to_string(),
+                        },
+                    };
+                    match Decimal::from_str(&strnum) {
+                        Ok(value, ..) => Ok(NumberCellData::from_decimal(value)),
+                        Err(_) => Ok(NumberCellData::new()),
+                    }
                 }
             }
             _ => NumberCellData::from_format_str(s, self.sign_positive, &self.format),
@@ -214,3 +231,11 @@ impl std::default::Default for NumberTypeOptionPB {
 lazy_static! {
     static ref NUM_REGEX: Regex = Regex::new(r"[^\d\.]").unwrap();
 }
+
+lazy_static! {
+    static ref SCIENTIFIC_NOTATION_REGEX: Regex = Regex::new(r"([+-]?\d*\.?\d+)e([+-]?\d+)").unwrap();
+}
+
+lazy_static! {
+    static ref EXTRACT_NUM_REGEX: Regex = Regex::new(r"^(\d+\.\d+)(?:\.\d+)*$").unwrap();
+}