瀏覽代碼

Add formatting options for Complex

Sigurd Kolltveit 9 年之前
父節點
當前提交
f138f3da9e
共有 1 個文件被更改,包括 46 次插入3 次删除
  1. 46 3
      complex/src/lib.rs

+ 46 - 3
complex/src/lib.rs

@@ -616,15 +616,49 @@ impl<T: Clone + Num> One for Complex<T> {
     }
 }
 
+macro_rules! write_complex {
+    ($f:ident, $re_fmt:expr, $im_fmt:expr, $re:expr, $im:expr, $( $arg:expr ),*) => {
+        if $im < Zero::zero() {
+            write!($f, concat!($re_fmt, "-", $im_fmt), $re, T::zero() - $im.clone(), $( $arg, )*)
+        } else {
+            write!($f, concat!($re_fmt, "+", $im_fmt), $re, $im, $( $arg, )*)
+        }
+    }
+}
+
 /* string conversions */
 impl<T> fmt::Display for Complex<T> where
     T: fmt::Display + Num + PartialOrd + Clone
 {
     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
-        if self.im < Zero::zero() {
-            write!(f, "{}-{}i", self.re, T::zero() - self.im.clone())
+        if let Some(precision) = f.precision() {
+            write_complex!(f, "{0:.2$}", "{1:.2$}i", self.re, self.im, precision)
+        } else {
+            write_complex!(f, "{0}", "{1}i", self.re, self.im,)
+        }
+    }
+}
+
+impl<T> fmt::LowerExp for Complex<T> where
+    T: fmt::LowerExp + Num + PartialOrd + Clone
+{
+    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
+        if let Some(precision) = f.precision() {
+            write_complex!(f, "{0:.2$e}", "{1:.2$e}i", self.re, self.im, precision)
         } else {
-            write!(f, "{}+{}i", self.re, self.im)
+            write_complex!(f, "{0:e}", "{1:e}i", self.re, self.im,)
+        }
+    }
+}
+
+impl<T> fmt::UpperExp for Complex<T> where
+    T: fmt::UpperExp + Num + PartialOrd + Clone
+{
+    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
+        if let Some(precision) = f.precision() {
+            write_complex!(f, "{0:.2$E}", "{1:.2$E}i", self.re, self.im, precision)
+        } else {
+            write_complex!(f, "{0:E}", "{1:E}i", self.re, self.im,)
         }
     }
 }
@@ -1210,6 +1244,15 @@ mod test {
         test(_05_05i, "0.5+0.5i".to_string());
     }
 
+    #[test]
+    fn test_string_formatting() {
+        let a: Complex64 = Complex::new(1.234567, 123.4567);
+        assert_eq!(format!("{}", a), "1.234567+123.4567i");
+        assert_eq!(format!("{:.2}", a), "1.23+123.46i");
+        assert_eq!(format!("{:.2E}", a), "1.23E0+1.23E2i");
+        assert_eq!(format!("{:e}", a), "1.234567e0+1.234567e2i");
+    }
+
     #[test]
     fn test_hash() {
         let a = Complex::new(0i32, 0i32);