简体   繁体   中英

Javascript - get milliseconds from float seconds

I got a string that represents seconds (eg value is "14.76580"). I want to set a new variable that has the value of the decimal portion (milliseconds) of that string ( eg x = 76580 ) and I'm not sure what's the best way to do that. May you help please ?

You can use this function to calculate the ms portion from a time (works on strings too):

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

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

To extract the decimal part from that string pattern . You can use string.split() function of Javascript.

Splits a String object into an array of strings by separating the string into substrings.

So ,

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

Just to add to the existing answers, you can also use a bit of arithmetic:

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

Since JS is so permissive, even this would work:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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