0

I am working on javascript here I am having some function which should pass all the test cases given in stackblitz. I just want to divide the number after point by 60

Here is the code so far I tried

 convert(min: any) {
    return min.split(".")[1] / 60;
  }

Any my input is

console.log(this.convert(2.0));
console.log(this.convert(2.15));
console.log(this.convert(2.3));
console.log(this.convert(2.45));

and my output should give like this

2.0
2.25
2.5
2.75

Any help?

Damian
  • 78
  • 3
kishan
  • 63
  • 7
  • Does this answer your question? [Get decimal portion of a number with JavaScript](https://stackoverflow.com/questions/4512306/get-decimal-portion-of-a-number-with-javascript) – Ivar Mar 31 '21 at 07:52
  • Thanks for the answer but its not helping me. – kishan Mar 31 '21 at 07:52
  • "Is not helping me" is not something we can work with. _Why_ is it not helping you? If you use that method to get the fraction of the number instead of `min.split(".")[1]` (which doesn't work because you can't call `.split()` on a number), it should work fine. – Ivar Mar 31 '21 at 07:54
  • @kishan, check out my updated answer. – Zunayed Shahriar Mar 31 '21 at 15:49

4 Answers4

0

You are trying to split a Number type. First convert your number to string, then split and then return it to number again. Refer the below function.

findHrsToMins(min: any) {
    min = String(min);
    return Number(min.split(".")[1] / 60);
  }
wahab memon
  • 2,193
  • 2
  • 10
  • 23
0

Function:

findHrsToMins(min: any) {
    const parts = min.toString().split(".");
    const mins = +parts[1];
    if (mins > 0 && mins < 10) mins *= 10; // Newly added
    return +parts[0] + (mins > 0 ? mins / 60 : 0);
}

Working demo at StackBlitz.

Zunayed Shahriar
  • 2,557
  • 2
  • 12
  • 15
0

Initial input is pretty weird in your case. I suppose x.59 is the maximum there. https://en.wikipedia.org/wiki/Sexagesimal

In current function you are returning only division after decimal and it is a division of fraction You need to add first part of the split (full hours) and get minutes instead of fraction of hour before division as well to get proper return.

function normalConvert(num: number){
    const [hour, hourFraction] = Number(num).toFixed(2).split(".")
    return +hour + ((+hourFraction * 100) / 60 / 100);
}
ecnaidar
  • 1
  • 1
0

I think you would have made it easier for yourself by typing the argument of the function, since that would help Typescript tell you what was going on.

findHrsToMins(min: number) {
    const hour = parseFloat(min.toString().split(".")[0]);

    const minutes = ((min * 100 - hour * 100) / 60).toFixed(2).split(".")[1];

    return `${hour}.${minutes}`;
  }
consager
  • 237
  • 1
  • 6