2013-05-28 104 views
3

我得到一个表示秒的字符串(例如,值是“14.76580”)。 我想设置一个新的变量,该变量的值是该字符串的小数部分(毫秒)(例如x = 76580),我不确定什么是最佳方式。 可以帮忙吗?Javascript - 从浮点秒获取毫秒

+0

您要在小数点之前移动多少小数? – 11684

+3

这是765.8,而不是76580毫秒。你真正想要的是什么? – Jon

+0

你的代码在哪里? –

回答

4

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

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

所以,

// 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); 
+0

我建议你使用'parseInt'来使它成为整数 –

+0

取点,没有公布,因为OP没有说他想把它转换成int。 – NINCOMPOOP

4

您可以使用此功能从时间计算毫秒部分(对字符串工作太):

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

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

+1漂亮的清洁解决方案:) – robertklep

+0

+1精确解决方案 – NINCOMPOOP

0

只需添加到现有的答案,你也可以使用一点算术:

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是如此宽容,所以即使这个窝uld工作:

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