2013-05-28 106 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);