File tree Expand file tree Collapse file tree 3 files changed +20
-2
lines changed Expand file tree Collapse file tree 3 files changed +20
-2
lines changed Original file line number Diff line number Diff line change 11# Changelog
22
3+ ## Unreleased
4+
5+ - Improved the precision of ` float.to_precision ` .
6+
37## v0.51.0 - 2024-12-22
48
59- ` dynamic/decode ` now has its own error type.
Original file line number Diff line number Diff line change @@ -261,8 +261,16 @@ pub fn truncate(x: Float) -> Int
261261/// ```
262262///
263263pub fn to_precision ( x : Float , precision : Int ) -> Float {
264- let factor = do_power ( 10.0 , do_to_float ( - precision ) )
265- do_to_float ( round ( x /. factor ) ) *. factor
264+ case precision <= 0 {
265+ True -> {
266+ let factor = do_power ( 10.0 , do_to_float ( - precision ) )
267+ do_to_float ( round ( x /. factor ) ) *. factor
268+ }
269+ False -> {
270+ let factor = do_power ( 10.0 , do_to_float ( precision ) )
271+ do_to_float ( round ( x *. factor ) ) /. factor
272+ }
273+ }
266274}
267275
268276@ external ( erlang , "erlang" , "float" )
Original file line number Diff line number Diff line change @@ -288,6 +288,12 @@ pub fn to_precision_test() {
288288
289289 float . to_precision ( 435.3224 , - 0)
290290 |> should . equal ( 435.0 )
291+
292+ float . to_precision ( 184.20000000000002 , 2 )
293+ |> should . equal ( 184.2 )
294+
295+ float . to_precision ( 12_345_678_912_345_678_912_345_678.0 , - 19)
296+ |> should . equal ( 1_234_568.0e19 )
291297}
292298
293299pub fn min_test ( ) {
You can’t perform that action at this time.
0 commit comments