@@ -678,6 +678,18 @@ impl d128 {
678678 d128:: with_context ( |ctx| unsafe { * decQuadQuantize ( & mut self , & self , other. as_ref ( ) , ctx) } )
679679 }
680680
681+ /// Same as the `quantize` function but allows a rounding mode to be specified.
682+ pub fn quantize_with_mode < O : AsRef < d128 > > ( mut self , other : O , mut rounding : Rounding ) -> d128 {
683+ use std:: mem;
684+
685+ d128:: with_context ( |ctx| {
686+ mem:: swap ( & mut ctx. rounding , & mut rounding) ;
687+ let result = unsafe { * decQuadQuantize ( & mut self , & self , other. as_ref ( ) , ctx) } ;
688+ mem:: swap ( & mut ctx. rounding , & mut rounding) ;
689+ result
690+ } )
691+ }
692+
681693 /// Returns a copy of `self` with its coefficient reduced to its shortest possible form without
682694 /// changing the value of the result. This removes all possible trailing zeros from the
683695 /// coefficient (some may remain when the number is very close to the most positive or most
@@ -1093,4 +1105,13 @@ mod tests {
10931105 assert_eq ! ( d128:: from_str( & ( :: std:: u64 :: MIN ) . to_string( ) ) . unwrap( ) ,
10941106 d128:: from( :: std:: u64 :: MIN ) ) ;
10951107 }
1108+
1109+ #[ test]
1110+ fn quantize_rounding ( ) {
1111+ assert_eq ! ( d128!( 2.0 ) , d128!( 1.5 ) . quantize_with_mode( d128!( 1 ) , Rounding :: HalfUp ) ) ;
1112+ assert_eq ! ( d128!( 3.0 ) , d128!( 2.5 ) . quantize_with_mode( d128!( 1 ) , Rounding :: HalfUp ) ) ;
1113+
1114+ assert_eq ! ( d128!( 2.0 ) , d128!( 2.9 ) . quantize_with_mode( d128!( 1 ) , Rounding :: Floor ) ) ;
1115+ assert_eq ! ( d128!( 3.0 ) , d128!( 2.1 ) . quantize_with_mode( d128!( 1 ) , Rounding :: Ceiling ) ) ;
1116+ }
10961117}
0 commit comments