Format numbers in JavaScript similar to C#

后端 未结 18 2298
傲寒
傲寒 2020-11-22 12:26

Is there a simple way to format numbers in JavaScript, similar to the formatting methods available in C# (or VB.NET) via ToString(\"format_provider\") or

18条回答
  •  悲&欢浪女
    2020-11-22 13:10

    I made a simple function, maybe someone can use it

    function secsToTime(secs){
      function format(number){
        if(number===0){
          return '00';
        }else {
          if (number < 10) {
              return '0' + number
          } else{
              return ''+number;
          }
        }
      }
    
      var minutes = Math.floor(secs/60)%60;
      var hours = Math.floor(secs/(60*60))%24;
      var days = Math.floor(secs/(60*60*24));
      var seconds = Math.floor(secs)%60;
    
      return (days>0? days+"d " : "")+format(hours)+':'+format(minutes)+':'+format(seconds);
    }
    

    this can generate the followings outputs:

    • 5d 02:53:39
    • 4d 22:15:16
    • 03:01:05
    • 00:00:00

提交回复
热议问题