Skip to content

Commit 0aa177d

Browse files
authored
Merge pull request RustPython#2307 from ChJR/feature/format_float
Fix default format(float) result when the number is too big
2 parents 25a388c + 3838610 commit 0aa177d

File tree

2 files changed

+17
-9
lines changed

2 files changed

+17
-9
lines changed

extra_tests/snippets/floats.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -487,6 +487,17 @@ def identical(x, y):
487487
assert float(1.2345678901234567890).__repr__() == "1.2345678901234567"
488488
assert float(1.2345678901234567890e308).__repr__() == "1.2345678901234567e+308"
489489

490+
assert format(1e15) == "1000000000000000.0"
491+
assert format(1e16) == "1e+16"
492+
assert format(1e308) == "1e+308"
493+
assert format(1e309) == "inf"
494+
assert format(1e-323) == "1e-323"
495+
assert format(1e-324) == "0.0"
496+
assert format(1e-5) == "1e-05"
497+
assert format(1e-4) == "0.0001"
498+
assert format(1.2345678901234567890) == "1.2345678901234567"
499+
assert format(1.2345678901234567890e308) == "1.2345678901234567e+308"
500+
490501
assert float('0_0') == 0.0
491502
assert float('.0') == 0.0
492503
assert float('0.') == 0.0

vm/src/format.rs

Lines changed: 6 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
use crate::builtins::pystr;
2+
use crate::common::float_ops;
23
use crate::exceptions::{IntoPyException, PyBaseExceptionRef};
34
use crate::function::FuncArgs;
45
use crate::pyobject::{ItemProtocol, PyObjectRef, PyResult, TypeProtocol};
@@ -399,15 +400,11 @@ impl FormatSpec {
399400
magnitude if magnitude.is_infinite() => Ok("inf%".to_owned()),
400401
_ => Ok(format!("{:.*}%", precision, magnitude * 100.0)),
401402
},
402-
None => {
403-
match magnitude {
404-
magnitude if magnitude.is_nan() => Ok("nan".to_owned()),
405-
magnitude if magnitude.is_infinite() => Ok("inf".to_owned()),
406-
// Using the Debug format here to prevent the automatic conversion of floats
407-
// ending in .0 to their integer representation (e.g., 1.0 -> 1)
408-
_ => Ok(format!("{:?}", magnitude)),
409-
}
410-
}
403+
None => match magnitude {
404+
magnitude if magnitude.is_nan() => Ok("nan".to_owned()),
405+
magnitude if magnitude.is_infinite() => Ok("inf".to_owned()),
406+
_ => Ok(float_ops::to_string(magnitude)),
407+
},
411408
};
412409

413410
if raw_magnitude_string_result.is_err() {

0 commit comments

Comments
 (0)