Javascript prototype function: decimal time value for time line

In the project I'm working on in JavaScript, I use decimal formats, so it’s easier to calculate, rather than using the hour / minute format in strings (a calendar-related project). However, to display the time on the user's screen, the time code must be displayed as hh: mm.

I thought it would be great to use the String prototype function for this, as this would allow me to use code like this:

var time = 8.75;
document.write("Meeting at "+time.toTime()); // writes: Meeting at 8:45

Until now, this has almost worked for me, using:

String.prototype.toTime = function(){
    var hrs = this.toString().slice(0,this.indexOf("."));
    var min = Math.round(this.toString().slice(this.indexOf("."))/100*60);
    min = min<10 ? "0"+min : min.toString();
    return hrs+":"+min;
}

The problem is that this will only work if the variable timeis a string. Otherwise, it will result in an undefined error.

- JavaScript, time.toString().toTime()?

!

+5
2

-, Number. , . , , .

-, , ...

Number.prototype.toTime = function(){
  var hrs = Math.floor(this)
  var min = Math.round(this%1*60)
  min = min<10 ? "0"+min : min.toString();
  return hrs+":"+min;
}

var time = 8.25;
console.log("Meeting at "+time.toTime());
+5

Object.prototype.toTime.

-1

All Articles