Skip to content

Commit 13acb1c

Browse files
authored
Precision bug fix when FormatType is None (RustPython#3975)
1 parent 8fa8194 commit 13acb1c

File tree

4 files changed

+18
-4
lines changed

4 files changed

+18
-4
lines changed

Lib/test/test_float.py

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -775,8 +775,6 @@ def test_format_testfile(self):
775775
self.assertEqual(fmt % float(arg), rhs)
776776
self.assertEqual(fmt % -float(arg), '-' + rhs)
777777

778-
# TODO: RUSTPYTHON
779-
@unittest.expectedFailure
780778
def test_issue5864(self):
781779
self.assertEqual(format(123.456, '.4'), '123.5')
782780
self.assertEqual(format(1234.56, '.4'), '1.235e+03')

common/src/float_ops.rs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -188,14 +188,15 @@ pub fn format_general(
188188
magnitude: f64,
189189
case: Case,
190190
alternate_form: bool,
191+
always_shows_fract: bool,
191192
) -> String {
192193
match magnitude {
193194
magnitude if magnitude.is_finite() => {
194195
let r_exp = format!("{:.*e}", precision.saturating_sub(1), magnitude);
195196
let mut parts = r_exp.splitn(2, 'e');
196197
let base = parts.next().unwrap();
197198
let exponent = parts.next().unwrap().parse::<i64>().unwrap();
198-
if exponent < -4 || exponent >= (precision as i64) {
199+
if exponent < -4 || exponent + (always_shows_fract as i64) >= (precision as i64) {
199200
let e = match case {
200201
Case::Lower => 'e',
201202
Case::Upper => 'E',

vm/src/cformat.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -348,6 +348,7 @@ impl CFormatSpec {
348348
magnitude,
349349
case,
350350
self.flags.contains(CConversionFlags::ALTERNATE_FORM),
351+
false,
351352
)
352353
}
353354
_ => unreachable!(),

vm/src/format.rs

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -379,6 +379,7 @@ impl FormatSpec {
379379
magnitude,
380380
float_ops::Case::Upper,
381381
false,
382+
false,
382383
))
383384
}
384385
Some(FormatType::GeneralFormatLower) => {
@@ -388,6 +389,7 @@ impl FormatSpec {
388389
magnitude,
389390
float_ops::Case::Lower,
390391
false,
392+
false,
391393
))
392394
}
393395
Some(FormatType::ExponentUpper) => Ok(float_ops::format_exponent(
@@ -408,7 +410,19 @@ impl FormatSpec {
408410
None => match magnitude {
409411
magnitude if magnitude.is_nan() => Ok("nan".to_owned()),
410412
magnitude if magnitude.is_infinite() => Ok("inf".to_owned()),
411-
_ => Ok(float_ops::to_string(magnitude)),
413+
_ => match self.precision {
414+
Some(_) => {
415+
let precision = self.precision.unwrap_or(magnitude.to_string().len() - 1);
416+
Ok(float_ops::format_general(
417+
precision,
418+
magnitude,
419+
float_ops::Case::Lower,
420+
false,
421+
true,
422+
))
423+
}
424+
None => Ok(float_ops::to_string(magnitude)),
425+
},
412426
},
413427
};
414428

0 commit comments

Comments
 (0)