ironwork_numeric/
float.rs1use crate::precision::{Fixed, Places};
6use zarch::check::{ProgramCheck, ProgramMask};
7use zarch::hfp::{Hfp, Precision, Rounding};
8use zarch::wide::U256;
9
10pub fn from_fixed(value: Fixed, precision: Precision, mask: ProgramMask) -> Result<Hfp, ProgramCheck> {
11 let magnitude = value.magnitude.to_u128().and_then(|m| i128::try_from(m).ok()).expect("a fixed-point operand fits 31 digits");
12 let integer = Hfp::from_integer(if value.negative { -magnitude } else { magnitude }, precision);
13 if value.places.dec == 0 {
14 return Ok(integer);
15 }
16 let scale = U256::pow10(value.places.dec).to_u128().expect("31 decimal places at most") as i128;
17 integer.div(Hfp::from_integer(scale, precision), mask)
18}
19
20pub fn to_fixed(value: Hfp, places: Places, rounded: bool) -> (Fixed, bool) {
22 let rounding = if rounded { Rounding::HalfAwayFromZero } else { Rounding::TowardZero };
23 match value.to_scaled_integer(places.dec, rounding) {
24 Some((negative, magnitude)) => {
25 let exact = Fixed { negative, magnitude, places: Places::new(u32::MAX / 2, places.dec) };
26 exact.to_receiver(places, false)
27 }
28 None => (Fixed::new(0, places), true),
29 }
30}
31
32pub fn narrow(value: Hfp, target: Precision) -> Hfp {
33 value.truncate(target)
34}
35
36#[cfg(test)]
37mod tests {
38 use super::*;
39
40 #[test]
41 fn a_decimal_fraction_becomes_a_truncated_quotient() {
42 let tenth = from_fixed(Fixed::new(1, Places::new(0, 1)), Precision::Long, ProgramMask::default()).unwrap();
43 assert_eq!(tenth.to_bytes(), 0x4019_9999_9999_9999u64.to_be_bytes());
44 }
45
46 #[test]
47 fn a_truncated_tenth_moves_back_as_zero_point_zero_nine() {
48 let tenth = Hfp::from_bytes(Precision::Long, &0x4019_9999_9999_9999u64.to_be_bytes());
49 assert_eq!(to_fixed(tenth, Places::new(1, 2), false).0.to_i128(), Some(9));
50 assert_eq!(to_fixed(tenth, Places::new(1, 2), true).0.to_i128(), Some(10));
51 }
52
53 #[test]
54 fn overflow_is_a_size_error() {
55 let big = Hfp::from_integer(123_456, Precision::Long);
56 assert!(to_fixed(big, Places::new(3, 0), false).1);
57 }
58}