diff --git a/extra_tests/snippets/floats.py b/extra_tests/snippets/floats.py index ce39be708b..18cbc2f426 100644 --- a/extra_tests/snippets/floats.py +++ b/extra_tests/snippets/floats.py @@ -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 diff --git a/vm/src/format.rs b/vm/src/format.rs index 9b0a6a0a08..963d7d0187 100644 --- a/vm/src/format.rs +++ b/vm/src/format.rs @@ -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}; @@ -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() {