@@ -554,19 +554,54 @@ impl<T: Clone + Num> One for Complex<T> {
554
554
}
555
555
}
556
556
557
+ macro_rules! write_complex {
558
+ ( $f: ident, $re_fmt: expr, $im_fmt: expr, $re: expr, $im: expr, $( $arg: expr ) ,* ) => {
559
+ if $im < Zero :: zero( ) {
560
+ write!( $f, concat!( $re_fmt, "-" , $im_fmt) , $re, T :: zero( ) - $im. clone( ) , $( $arg, ) * )
561
+ } else {
562
+ write!( $f, concat!( $re_fmt, "+" , $im_fmt) , $re, $im, $( $arg, ) * )
563
+ }
564
+ }
565
+ }
566
+
557
567
/* string conversions */
558
568
impl < T > fmt:: Display for Complex < T > where
559
569
T : fmt:: Display + Num + PartialOrd + Clone
560
570
{
561
571
fn fmt ( & self , f : & mut fmt:: Formatter ) -> fmt:: Result {
562
- if self . im < Zero :: zero ( ) {
563
- write ! ( f, "{}-{}i" , self . re, T :: zero( ) - self . im. clone( ) )
572
+ if let Some ( precision) = f. precision ( ) {
573
+ write_complex ! ( f, "{0:.2$}" , "{1:.2$}i" , self . re, self . im, precision)
574
+ } else {
575
+ write_complex ! ( f, "{0}" , "{1}i" , self . re, self . im, )
576
+ }
577
+ }
578
+ }
579
+
580
+ impl < T > fmt:: LowerExp for Complex < T > where
581
+ T : fmt:: LowerExp + Num + PartialOrd + Clone
582
+ {
583
+ fn fmt ( & self , f : & mut fmt:: Formatter ) -> fmt:: Result {
584
+ if let Some ( precision) = f. precision ( ) {
585
+ write_complex ! ( f, "{0:.2$e}" , "{1:.2$e}i" , self . re, self . im, precision)
564
586
} else {
565
- write ! ( f, "{}+{ }i" , self . re, self . im)
587
+ write_complex ! ( f, "{0:e}" , "{1:e }i", self . re, self . im, )
566
588
}
567
589
}
568
590
}
569
591
592
+ impl < T > fmt:: UpperExp for Complex < T > where
593
+ T : fmt:: UpperExp + Num + PartialOrd + Clone
594
+ {
595
+ fn fmt ( & self , f : & mut fmt:: Formatter ) -> fmt:: Result {
596
+ if let Some ( precision) = f. precision ( ) {
597
+ write_complex ! ( f, "{0:.2$E}" , "{1:.2$E}i" , self . re, self . im, precision)
598
+ } else {
599
+ write_complex ! ( f, "{0:E}" , "{1:E}i" , self . re, self . im, )
600
+ }
601
+ }
602
+ }
603
+
604
+
570
605
#[ cfg( test) ]
571
606
mod test {
572
607
#![ allow( non_upper_case_globals) ]
@@ -1070,6 +1105,15 @@ mod test {
1070
1105
test ( _05_05i, "0.5+0.5i" . to_string ( ) ) ;
1071
1106
}
1072
1107
1108
+ #[ test]
1109
+ fn test_string_formatting ( ) {
1110
+ let a: Complex64 = Complex :: new ( 1.234567 , 123.4567 ) ;
1111
+ assert_eq ! ( format!( "{}" , a) , "1.234567+123.4567i" ) ;
1112
+ assert_eq ! ( format!( "{:.2}" , a) , "1.23+123.46i" ) ;
1113
+ assert_eq ! ( format!( "{:.2E}" , a) , "1.23E0+1.23E2i" ) ;
1114
+ assert_eq ! ( format!( "{:e}" , a) , "1.234567e0+1.234567e2i" ) ;
1115
+ }
1116
+
1073
1117
#[ test]
1074
1118
fn test_hash ( ) {
1075
1119
let a = Complex :: new ( 0i32 , 0i32 ) ;
0 commit comments