rustils/parse/float.rs
1use error::ParseError;
2use RoundingMode;
3
4pub trait ToF32 {
5
6 fn to_f32_res(self)
7 -> ParseResultF32;
8
9 fn to_f32(self)
10 -> f32;
11}
12
13pub trait ToF32RM {
14
15 fn to_f32_rm_res(self, rm: RoundingMode)
16 -> ParseResultF32;
17
18 fn to_f32_rm(self, rm: RoundingMode)
19 -> f32;
20}
21
22/// Parse [`bool`](https://doc.rust-lang.org/std/primitive.bool.html) to
23/// [`f32`](https://doc.rust-lang.org/std/primitive.f32.html)
24///
25/// If `a` is `false` then returns `Ok(0.0)`.<br>
26/// If `a` is `true` then returns `Ok(1.0)`.
27///
28/// # Arguments
29///
30/// * `a` - [`bool`](https://doc.rust-lang.org/std/primitive.bool.html)
31///
32/// # Examples
33///
34/// ```
35/// use rustils::parse::float::bool_to_f32_res;
36///
37/// assert_eq!(bool_to_f32_res(true), Ok(1.0_f32));
38/// assert_eq!(bool_to_f32_res(false), Ok(0.0_f32));
39/// ```
40pub fn bool_to_f32_res(a: bool)
41 -> ParseResultF32 {
42
43 if a { Ok(1.0) } else { Ok(0.0) }
44}
45
46/// Parse [`bool`](https://doc.rust-lang.org/std/primitive.bool.html) to
47/// [`f32`](https://doc.rust-lang.org/std/primitive.f32.html)
48///
49/// If `a` is `false` then returns 0.0.<br>
50/// If `a` is `true` then returns 1.0.
51///
52/// # Arguments
53///
54/// * `a` - [`bool`](https://doc.rust-lang.org/std/primitive.bool.html)
55///
56/// # Examples
57///
58/// ```
59/// use rustils::parse::float::bool_to_f32;
60///
61/// assert_eq!(bool_to_f32(true), 1.0_f32);
62/// assert_eq!(bool_to_f32(false), 0.0_f32);
63/// ```
64pub fn bool_to_f32(a: bool)
65 -> f32 {
66
67 if a { 1.0 } else { 0.0 }
68}
69
70pub fn string_to_f32_res(a: String)
71 -> ParseResultF32 {
72
73 match a.parse::<f32>() {
74 Ok(n) => Ok(n),
75 Err(_) => Err(ParseError::InvalidNumber(a))
76 }
77}
78
79pub fn string_to_f32(a: String)
80 -> f32 {
81
82 match string_to_f32_res(a) {
83 Ok(i) => i,
84 Err(err) => panic!("{}",err)
85 }
86}
87
88pub fn str_to_f32_res(a: &str)
89 -> ParseResultF32 {
90
91 match a.parse::<f32>() {
92 Ok(n) => Ok(n),
93 Err(_) => Err(ParseError::InvalidNumber(a.to_string()))
94 }
95}
96
97pub fn str_to_f32(a: &str)
98 -> f32 {
99
100 match str_to_f32_res(a) {
101 Ok(i) => i,
102 Err(err) => panic!("{}",err)
103 }
104}
105
106pub type ParseResultF32 = Result<f32, ParseError>;