Skip to content

Commit c951cb3

Browse files
committed
float.__round__ for ndigits == 0
1 parent b7c7591 commit c951cb3

File tree

2 files changed

+22
-3
lines changed

2 files changed

+22
-3
lines changed

tests/snippets/floats.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -114,6 +114,14 @@
114114
assert math.trunc(1.2) == 1
115115
assert_raises(OverflowError, float('inf').__trunc__)
116116
assert_raises(ValueError, float('nan').__trunc__)
117+
assert 0.5.__round__() == 0.0
118+
assert 1.5.__round__() == 2.0
119+
assert 0.5.__round__(0) == 0.0
120+
assert 1.5.__round__(0) == 2.0
121+
assert 0.5.__round__(None) == 0.0
122+
assert 1.5.__round__(None) == 2.0
123+
assert_raises(OverflowError, float('inf').__round__)
124+
assert_raises(ValueError, float('nan').__round__)
117125

118126
assert (1.7).real == 1.7
119127
assert (1.3).is_integer() == False

vm/src/obj/objfloat.rs

Lines changed: 14 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ use crate::pyobject::{
1111
use crate::vm::VirtualMachine;
1212
use num_bigint::{BigInt, ToBigInt};
1313
use num_rational::Ratio;
14-
use num_traits::ToPrimitive;
14+
use num_traits::{ToPrimitive, Zero};
1515

1616
#[pyclass(name = "float")]
1717
#[derive(Debug, Copy, Clone, PartialEq)]
@@ -387,8 +387,19 @@ impl PyFloat {
387387
OptionalArg::Missing => None,
388388
OptionalArg::Present(ref value) => {
389389
if !vm.get_none().is(value) {
390-
// retrive int to implement it
391-
Some(vm.ctx.not_implemented())
390+
let ndigits = if objtype::isinstance(value, &vm.ctx.int_type()) {
391+
objint::get_value(value)
392+
} else {
393+
return Err(vm.new_type_error(format!(
394+
"TypeError: '{}' object cannot be interpreted as an integer",
395+
value.class().name
396+
)));
397+
};
398+
if ndigits.is_zero() {
399+
None
400+
} else {
401+
Some(ndigits)
402+
}
392403
} else {
393404
None
394405
}

0 commit comments

Comments
 (0)