首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >将毫秒从3位数字改为2位数字

将毫秒从3位数字改为2位数字
EN

Stack Overflow用户
提问于 2016-01-03 23:48:55
回答 3查看 4.1K关注 0票数 2

我在制作秒表时遇到了问题,它只使用2位数的毫秒部分。我有完整的JSFiddle 这里。我需要一些帮助的函数是formatter()方法。

现在,该方法如下所示:

代码语言:javascript
复制
formatter(timeInMilliseconds) {
  const padZero = (time) => {
    while (time.length < 2) { 
      time = '0' + time; 
    } 
    return time;
  }

  let time = new Date(timeInMilliseconds);
  let minutes = padZero(time.getMinutes().toString());
  let seconds = padZero(time.getSeconds().toString());
  let milliseconds = padZero((time.getMilliseconds() / 10).toFixed(0));

  let output = `${minutes} : ${seconds} . ${milliseconds}`;
  console.log(output);
  return output;
} 

在大多数情况下,它是有效的。但是,如果您在计时器运行时查看我的JSFiddle的控制台,那么这个问题是显而易见的。例如,如果秒表当前处于类似于00 : 15 . 99的位置,那么它将在下一个滴答时变成00 : 15 . 100,而不是00 : 16 . 00

任何帮助都将不胜感激。

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2016-01-03 23:53:56

toFixed循环而不是截断,因此995毫秒及更长的时间将变成99.5,并由toFixed格式化为100。您可以将其转换为整数,然后转换为字符串以截断它:

代码语言:javascript
复制
let milliseconds = padZero('' + (time.getMilliseconds() / 10 | 0));

padZero接受一个数字而不是一个字符串也可能是一个很好的简化:

代码语言:javascript
复制
function padZero(time) {
    return time < 10 ? '0' + time : '' + time;
}

let time = new Date(timeInMilliseconds);
let minutes = padZero(time.getMinutes());
let seconds = padZero(time.getSeconds());
let milliseconds = padZero(time.getMilliseconds() / 10 | 0);

let output = `${minutes} : ${seconds} . ${milliseconds}`;

最后,如果timeInMilliseconds不是自1970-01-01 00:00:00开始的时间戳(以毫秒为单位),而是一个持续时间,那么将其转换为Date是不合适的。算一算:

代码语言:javascript
复制
const minutes = padZero(timeInMilliseconds / 60000 | 0);
const seconds = padZero((timeInMilliseconds / 1000 | 0) % 60);
const centiseconds = padZero((timeInMilliseconds / 10 | 0) % 100);
票数 4
EN

Stack Overflow用户

发布于 2016-01-03 23:54:24

您的问题是.toFixed()循环而不是截断。

代码语言:javascript
复制
(99.4).toFixed(0) == '99'
(99.5).toFixed(0) == '100'

你要做的就是替换

代码语言:javascript
复制
(time.getMilliseconds() / 10).toFixed(0)

使用

代码语言:javascript
复制
Math.floor(time.getMilliseconds() / 10).toFixed(0)

而且会成功的。

票数 2
EN

Stack Overflow用户

发布于 2016-01-03 23:51:37

您可以使用子字符串()

代码语言:javascript
复制
let milliseconds = padZero((time.getMilliseconds() / 10).toFixed(0)).substr(0, 2);
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/34582986

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档