Skip to content

Commit da99676

Browse files
committed
Add formatting options for Complex
1 parent 9079b88 commit da99676

File tree

1 file changed

+47
-3
lines changed

1 file changed

+47
-3
lines changed

src/complex.rs

Lines changed: 47 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -554,19 +554,54 @@ impl<T: Clone + Num> One for Complex<T> {
554554
}
555555
}
556556

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+
557567
/* string conversions */
558568
impl<T> fmt::Display for Complex<T> where
559569
T: fmt::Display + Num + PartialOrd + Clone
560570
{
561571
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)
564586
} else {
565-
write!(f, "{}+{}i", self.re, self.im)
587+
write_complex!(f, "{0:e}", "{1:e}i", self.re, self.im,)
566588
}
567589
}
568590
}
569591

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+
570605
#[cfg(test)]
571606
mod test {
572607
#![allow(non_upper_case_globals)]
@@ -1070,6 +1105,15 @@ mod test {
10701105
test(_05_05i, "0.5+0.5i".to_string());
10711106
}
10721107

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+
10731117
#[test]
10741118
fn test_hash() {
10751119
let a = Complex::new(0i32, 0i32);

0 commit comments

Comments
 (0)