mirror of
https://github.com/vlang/v.git
synced 2023-08-10 21:13:21 +03:00
math: add round_sig function for f64 (#14997)
This commit is contained in:
parent
c5a290ffc6
commit
7e1c45ab44
@ -75,6 +75,35 @@ pub fn round(x f64) f64 {
|
|||||||
return y
|
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.
|
// round_to_even returns the nearest integer, rounding ties to even.
|
||||||
//
|
//
|
||||||
// special cases are:
|
// special cases are:
|
||||||
|
@ -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() {
|
fn test_sin() {
|
||||||
for i := 0; i < math.vf_.len; i++ {
|
for i := 0; i < math.vf_.len; i++ {
|
||||||
f := sin(math.vf_[i])
|
f := sin(math.vf_[i])
|
||||||
|
Loading…
Reference in New Issue
Block a user