Skip to content

Commit

Permalink
improve precision
Browse files Browse the repository at this point in the history
  • Loading branch information
joshi-monster authored and lpil committed Jan 3, 2025
1 parent f9aea4a commit 619935a
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 2 deletions.
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
# Changelog

## Unreleased

- Improved the precision of `float.to_precision`.

## v0.51.0 - 2024-12-22

- `dynamic/decode` now has its own error type.
Expand Down
12 changes: 10 additions & 2 deletions src/gleam/float.gleam
Original file line number Diff line number Diff line change
Expand Up @@ -261,8 +261,16 @@ pub fn truncate(x: Float) -> Int
/// ```
///
pub fn to_precision(x: Float, precision: Int) -> Float {
let factor = do_power(10.0, do_to_float(-precision))
do_to_float(round(x /. factor)) *. factor
case precision <= 0 {
True -> {
let factor = do_power(10.0, do_to_float(-precision))
do_to_float(round(x /. factor)) *. factor
}
False -> {
let factor = do_power(10.0, do_to_float(precision))
do_to_float(round(x *. factor)) /. factor
}
}
}

@external(erlang, "erlang", "float")
Expand Down
6 changes: 6 additions & 0 deletions test/gleam/float_test.gleam
Original file line number Diff line number Diff line change
Expand Up @@ -288,6 +288,12 @@ pub fn to_precision_test() {

float.to_precision(435.3224, -0)
|> should.equal(435.0)

float.to_precision(184.20000000000002, 2)
|> should.equal(184.2)

float.to_precision(12_345_678_912_345_678_912_345_678.0, -19)
|> should.equal(1_234_568.0e19)
}

pub fn min_test() {
Expand Down

0 comments on commit 619935a

Please sign in to comment.