Skip to content

Fix default format(float) result when the number is too big #2307

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Oct 26, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions extra_tests/snippets/floats.py
Original file line number Diff line number Diff line change
Expand Up @@ -487,6 +487,17 @@ def identical(x, y):
assert float(1.2345678901234567890).__repr__() == "1.2345678901234567"
assert float(1.2345678901234567890e308).__repr__() == "1.2345678901234567e+308"

assert format(1e15) == "1000000000000000.0"
assert format(1e16) == "1e+16"
assert format(1e308) == "1e+308"
assert format(1e309) == "inf"
assert format(1e-323) == "1e-323"
assert format(1e-324) == "0.0"
assert format(1e-5) == "1e-05"
assert format(1e-4) == "0.0001"
assert format(1.2345678901234567890) == "1.2345678901234567"
assert format(1.2345678901234567890e308) == "1.2345678901234567e+308"

assert float('0_0') == 0.0
assert float('.0') == 0.0
assert float('0.') == 0.0
Expand Down
15 changes: 6 additions & 9 deletions vm/src/format.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use crate::builtins::pystr;
use crate::common::float_ops;
use crate::exceptions::{IntoPyException, PyBaseExceptionRef};
use crate::function::FuncArgs;
use crate::pyobject::{ItemProtocol, PyObjectRef, PyResult, TypeProtocol};
Expand Down Expand Up @@ -399,15 +400,11 @@ impl FormatSpec {
magnitude if magnitude.is_infinite() => Ok("inf%".to_owned()),
_ => Ok(format!("{:.*}%", precision, magnitude * 100.0)),
},
None => {
match magnitude {
magnitude if magnitude.is_nan() => Ok("nan".to_owned()),
magnitude if magnitude.is_infinite() => Ok("inf".to_owned()),
// Using the Debug format here to prevent the automatic conversion of floats
// ending in .0 to their integer representation (e.g., 1.0 -> 1)
_ => Ok(format!("{:?}", magnitude)),
}
}
None => match magnitude {
magnitude if magnitude.is_nan() => Ok("nan".to_owned()),
magnitude if magnitude.is_infinite() => Ok("inf".to_owned()),
_ => Ok(float_ops::to_string(magnitude)),
},
};

if raw_magnitude_string_result.is_err() {
Expand Down