Merge pull request #1551 from ChJR/feature/float-repr

Fix float.__repr__()
This commit is contained in:
Windel Bouwman
2019-10-20 21:14:09 +02:00
committed by GitHub
2 changed files with 25 additions and 2 deletions

View File

@@ -289,3 +289,14 @@ assert float('nan').__eq__(float('nan')) is False
assert float('nan').__ne__(float('nan')) is True
assert float('nan').__eq__(float('inf')) is False
assert float('nan').__ne__(float('inf')) is True
assert float(1e15).__repr__() == "1000000000000000.0"
assert float(1e16).__repr__() == "1e+16"
assert float(1e308).__repr__() == "1e+308"
assert float(1e309).__repr__() == "inf"
assert float(1e-323).__repr__() == "1e-323"
assert float(1e-324).__repr__() == "0.0"
assert float(1e-5).__repr__() == "1e-05"
assert float(1e-4).__repr__() == "0.0001"
assert float(1.2345678901234567890).__repr__() == "1.2345678901234567"
assert float(1.2345678901234567890e308).__repr__() == "1.2345678901234567e+308"

View File

@@ -416,8 +416,20 @@ impl PyFloat {
#[pymethod(name = "__repr__")]
fn repr(&self, vm: &VirtualMachine) -> String {
if self.is_integer(vm) {
format!("{:.1?}", self.value)
let value = format!("{:e}", self.value);
if let Some(position) = value.find('e') {
let significand = &value[..position];
let exponent = &value[position + 1..];
let exponent = exponent.parse::<i32>().unwrap();
if exponent < 16 && exponent > -5 {
if self.is_integer(vm) {
format!("{:.1?}", self.value)
} else {
self.value.to_string()
}
} else {
format!("{}e{:+#03}", significand, exponent)
}
} else {
self.value.to_string()
}