Skip to content

Commit 7ba9556

Browse files
committed
Add format %e option of floating point numbers.
1 parent a8285f4 commit 7ba9556

File tree

1 file changed

+24
-1
lines changed

1 file changed

+24
-1
lines changed

vm/src/cformat.rs

Lines changed: 24 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -242,6 +242,24 @@ impl CFormatSpec {
242242
}
243243
}
244244

245+
fn normalize_float(&self, num: f64) -> (f64, i32) {
246+
let mut fraction = num;
247+
let mut exponent = 0;
248+
loop {
249+
if fraction >= 10.0 {
250+
fraction = fraction / 10.0;
251+
exponent = exponent + 1;
252+
} else if fraction < 1.0 && fraction > 0.0 {
253+
fraction = fraction * 10.0;
254+
exponent = exponent - 1;
255+
} else {
256+
break;
257+
}
258+
}
259+
260+
(fraction, exponent)
261+
}
262+
245263
pub(crate) fn format_float(&self, num: f64) -> Result<String, String> {
246264
let sign_string = if num.is_sign_positive() {
247265
self.flags.sign_string()
@@ -259,7 +277,12 @@ impl CFormatSpec {
259277
Ok(format!("{:.*}", precision, magnitude))
260278
}
261279
CFormatType::Float(CFloatType::Exponent(_)) => {
262-
Err("Not yet implemented for %e and %E".to_owned())
280+
let precision = match self.precision {
281+
Some(CFormatQuantity::Amount(p)) => p,
282+
_ => 6,
283+
};
284+
let (fraction, exponent) = self.normalize_float(num.abs());
285+
Ok(format!("{:.*}e{:+03}", precision, fraction, exponent))
263286
}
264287
CFormatType::Float(CFloatType::General(_)) => {
265288
Err("Not yet implemented for %g and %G".to_owned())

0 commit comments

Comments
 (0)