繁体   English   中英

Javascript-从浮动秒数获取毫秒数

[英]Javascript - get milliseconds from float seconds

我得到了代表秒的字符串(例如,值是“ 14.76580”)。 我想设置一个新变量,该变量具有该字符串的小数部分(毫秒)的值(例如x = 76580),但我不确定执行此操作的最佳方法是什么。 你能帮忙吗?

您可以使用此函数来计算某个时间的ms部分(也适用于字符串):

function getMilliSeconds(num)
{
    return (num % 1) * 1000;
}

getMilliSeconds(1.123); // 123
getMilliSeconds(14.76580); // 765.8000000000005

从该字符串模式中提取小数部分。 您可以使用Javascript的string.split()函数。

通过将字符串对象拆分为子字符串,将String对象拆分为字符串数组。

所以,

// splits the string into two elements "14" and "76580"    
var arr = "14.76580".split("."); 
// gives the decimal part
var x = arr[1];
// convert it to Integer
var y = parseInt(x,10);

只需添加一些现有的答案,就可以使用一些算法:

var a = parseFloat(14.76580);//get the number as a float
var b = Math.floor(a);//get the whole part
var c = a-b;//get the decimal part by substracting the whole part from the full float value

由于JS如此宽容,所以即使这样也可以:

var value = "14.76580";
var decimal = value-parseInt(value);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM