From 7e1c45ab44be3c2a3a10716ced8818f2004be45f Mon Sep 17 00:00:00 2001 From: CC Date: Sat, 9 Jul 2022 01:41:58 -0600 Subject: [PATCH] math: add round_sig function for f64 (#14997) --- vlib/math/floor.v | 29 +++++++++++++++++++++++++++++ vlib/math/math_test.v | 11 +++++++++++ 2 files changed, 40 insertions(+) diff --git a/vlib/math/floor.v b/vlib/math/floor.v index a2c3208e3c..bfaf6607e2 100644 --- a/vlib/math/floor.v +++ b/vlib/math/floor.v @@ -75,6 +75,35 @@ pub fn round(x f64) f64 { return y } +// Returns the rounded float, with sig_digits of precision. +// i.e `assert round_sig(4.3239437319748394,6) == 4.323944` +pub fn round_sig(x f64, sig_digits int) f64 { + mut ret_str := '$x' + + match sig_digits { + 0 { ret_str = '${x:0.0f}' } + 1 { ret_str = '${x:0.1f}' } + 2 { ret_str = '${x:0.2f}' } + 3 { ret_str = '${x:0.3f}' } + 4 { ret_str = '${x:0.4f}' } + 5 { ret_str = '${x:0.5f}' } + 6 { ret_str = '${x:0.6f}' } + 7 { ret_str = '${x:0.7f}' } + 8 { ret_str = '${x:0.8f}' } + 9 { ret_str = '${x:0.9f}' } + 10 { ret_str = '${x:0.10f}' } + 11 { ret_str = '${x:0.11f}' } + 12 { ret_str = '${x:0.12f}' } + 13 { ret_str = '${x:0.13f}' } + 14 { ret_str = '${x:0.14f}' } + 15 { ret_str = '${x:0.15f}' } + 16 { ret_str = '${x:0.16f}' } + else { ret_str = '$x' } + } + + return ret_str.f64() +} + // round_to_even returns the nearest integer, rounding ties to even. // // special cases are: diff --git a/vlib/math/math_test.v b/vlib/math/math_test.v index fc2d16cd17..93cf6792ef 100644 --- a/vlib/math/math_test.v +++ b/vlib/math/math_test.v @@ -808,6 +808,17 @@ fn test_round() { } } +fn fn_test_round_sig() { + assert round_sig(4.3239437319748394, -1) == 4.3239437319748394 + assert round_sig(4.3239437319748394, 0) == 4.0000000000000000 + assert round_sig(4.3239437319748394, 1) == 4.3000000000000000 + assert round_sig(4.3239437319748394, 2) == 4.3200000000000000 + assert round_sig(4.3239437319748394, 3) == 4.3240000000000000 + assert round_sig(4.3239437319748394, 6) == 4.3239440000000000 + assert round_sig(4.3239437319748394, 12) == 4.323943731975 + assert round_sig(4.3239437319748394, 17) == 4.3239437319748394 +} + fn test_sin() { for i := 0; i < math.vf_.len; i++ { f := sin(math.vf_[i])