Skip to content

Commit

Permalink
fix(rust, python): Don't upcast in round() for f32 when decimal is 0 (#…
Browse files Browse the repository at this point in the history
  • Loading branch information
mcrumiller authored May 7, 2023
1 parent 3ee421d commit 98cfa93
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 8 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -295,7 +295,7 @@ mod test {
reset_string_cache();
enable_string_cache(false);

// tests several things that may loose the dtype information
// tests several things that may lose the dtype information
let s = Series::new("a", vec!["a", "b", "c"]).cast(&DataType::Categorical(None))?;

assert_eq!(
Expand Down
19 changes: 12 additions & 7 deletions polars/polars-core/src/series/ops/round.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,18 @@ impl Series {
/// Round underlying floating point array to given decimal.
pub fn round(&self, decimals: u32) -> PolarsResult<Self> {
if let Ok(ca) = self.f32() {
// Note we do the computation on f64 floats to not loose precision
// when the computation is done, we cast to f32
let multiplier = 10.0.pow(decimals as f64);
let s = ca
.apply(|val| ((val as f64 * multiplier).round() / multiplier) as f32)
.into_series();
return Ok(s);
if decimals == 0 {
let s = ca.apply(|val| val.round()).into_series();
return Ok(s);
} else {
// Note we do the computation on f64 floats to not lose precision
// when the computation is done, we cast to f32
let multiplier = 10.0.pow(decimals as f64);
let s = ca
.apply(|val| ((val as f64 * multiplier).round() / multiplier) as f32)
.into_series();
return Ok(s);
}
}
if let Ok(ca) = self.f64() {
let multiplier = 10.0.pow(decimals as f64);
Expand Down

0 comments on commit 98cfa93

Please sign in to comment.