repl.it
@ASutton1986/

ceil, round, floor

JavaScript

No description

fork
loading
main.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
//https://www.codewars.com/kata/5267faf57526ea542e0007fb/train/javascript
// Oh no, our Math object was "accidently" reset. Can you re-implement some of those functions? We can assure, that only non-negative numbers are passed as arguments. So you don't have to consider things like undefined, null, NaN, negative numbers, strings and so on.

// Here is a list of functions, we need:

// Math.round()
// Math.ceil()
// Math.floor()

// Example Tests:

// 1
// Test.assertEquals(Math.round(0.4), 0, 'Math.round(0.4)');
// 2
// Test.assertEquals(Math.round(0.5), 1, 'Math.round(0.5)');
// 3
// ​
// 4
// Test.assertEquals(Math.ceil(0.4), 1, 'Math.ceil(0.4)');
// 5
// Test.assertEquals(Math.ceil(0.5), 1, 'Math.ceil(0.5)');
// 6
// ​
// 7
// Test.assertEquals(Math.floor(0.4), 0, 'Math.floor(0.4)');
// 8
// Test.assertEquals(Math.floor(0.5), 0, 'Math.floor(0.5)');

Math.round = function(number) {
  //if number has a decimal point
  if(number % 1 !== 0){
    var arr = number.toString().split('.');
    if(arr[1].split('')[0] >= 5){
      return (arr[0]*1 + 1);
    }else{
      return (arr[0]*1);
    }
  }else{
    //if its an integer then return the number itself
    return number;
  }
};

Math.ceil = function(number) {
  if(number % 1 !== 0){
    return (number.toString().split('.')[0]*1 + 1);
  }else{
    return number;
  }
};

Math.floor = function(number) {
  if(number % 1 !== 0){
    return (number.toString().split('.')[0]*1);
  }else{
    return number;
  }
};

//Math.floor(13.4);
//Math.round(2.499);
//Math.round(0.5);
Math.ceil(5);
Native Browser JavaScript