File tree Expand file tree Collapse file tree 1 file changed +16
-4
lines changed Expand file tree Collapse file tree 1 file changed +16
-4
lines changed Original file line number Diff line number Diff line change 2
2
// Source: https://en.wikipedia.org/wiki/Floor_and_ceiling_functions
3
3
4
4
pub fn ceil ( x : f64 ) -> f64 {
5
- let x_round = x. round ( ) ;
6
- if ( x_round * 10.0 ) . round ( ) < ( x * 10.0 ) . round ( ) {
7
- x_round + 1.0
5
+ let x_rounded_towards_zero = x as i32 as f64 ;
6
+ if x < 0. || x_rounded_towards_zero == x {
7
+ x_rounded_towards_zero
8
8
} else {
9
- x_round
9
+ x_rounded_towards_zero + 1_f64
10
10
}
11
11
}
12
12
@@ -20,6 +20,12 @@ mod tests {
20
20
assert_eq ! ( ceil( num) , num. ceil( ) ) ;
21
21
}
22
22
23
+ #[ test]
24
+ fn positive_decimal_with_small_number ( ) {
25
+ let num = 3.01 ;
26
+ assert_eq ! ( ceil( num) , num. ceil( ) ) ;
27
+ }
28
+
23
29
#[ test]
24
30
fn positive_integer ( ) {
25
31
let num = 1.00 ;
@@ -32,6 +38,12 @@ mod tests {
32
38
assert_eq ! ( ceil( num) , num. ceil( ) ) ;
33
39
}
34
40
41
+ #[ test]
42
+ fn negative_decimal_with_small_number ( ) {
43
+ let num = -1.01 ;
44
+ assert_eq ! ( ceil( num) , num. ceil( ) ) ;
45
+ }
46
+
35
47
#[ test]
36
48
fn negative_integer ( ) {
37
49
let num = -1.00 ;
You can’t perform that action at this time.
0 commit comments