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 1
1
# Changelog
2
2
3
+ ## Unreleased
4
+
5
+ - Improved the precision of ` float.to_precision ` .
6
+
3
7
## v0.51.0 - 2024-12-22
4
8
5
9
- ` 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
261
261
/// ```
262
262
///
263
263
pub 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
+ }
266
274
}
267
275
268
276
@ external ( erlang , "erlang" , "float" )
Original file line number Diff line number Diff line change @@ -288,6 +288,12 @@ pub fn to_precision_test() {
288
288
289
289
float . to_precision ( 435.3224 , - 0)
290
290
|> 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 )
291
297
}
292
298
293
299
pub fn min_test ( ) {
You can’t perform that action at this time.
0 commit comments