Support underscores in Dec numbers

Closes #5303
This commit is contained in:
Ayaz Hafiz 2023-04-19 11:27:12 -05:00
parent ef5c4735fb
commit c497641e63
No known key found for this signature in database
GPG key ID: 0E2A37416A25EF58
3 changed files with 33 additions and 6 deletions

View file

@ -298,12 +298,36 @@ impl RocDec {
}; };
// Calculate the high digits - the ones before the decimal point. // Calculate the high digits - the ones before the decimal point.
match before_point.parse::<i128>() { let (is_pos, digits) = match before_point.chars().next() {
Ok(answer) => match answer.checked_mul(Self::ONE_POINT_ZERO) { Some('+') => (true, &before_point[1..]),
Some(hi) => hi.checked_add(lo).map(|num| Self(num.to_ne_bytes())), Some('-') => (false, &before_point[1..]),
None => None, _ => (true, before_point),
}, };
Err(_) => None,
let mut hi: i128 = 0;
macro_rules! adjust_hi {
($op:ident) => {{
for digit in digits.chars() {
if digit == '_' {
continue;
}
let digit = digit.to_digit(10)?;
hi = hi.checked_mul(10)?;
hi = hi.$op(digit as _)?;
}
}};
}
if is_pos {
adjust_hi!(checked_add);
} else {
adjust_hi!(checked_sub);
}
match hi.checked_mul(Self::ONE_POINT_ZERO) {
Some(hi) => hi.checked_add(lo).map(|num| Self(num.to_ne_bytes())),
None => None,
} }
} }

View file

@ -295,6 +295,9 @@ mod test_roc_std {
let example = RocDec::from_str("1234.5678").unwrap(); let example = RocDec::from_str("1234.5678").unwrap();
assert_eq!(format!("{}", example), "1234.5678"); assert_eq!(format!("{}", example), "1234.5678");
let example = RocDec::from_str("1_000.5678").unwrap();
assert_eq!(format!("{}", example), "1000.5678");
} }
#[test] #[test]