Reputation: 1695
I have a javascript number 12.1542. and I want the new string 12.(1542*60) from this string.
How can I get it. Thanks
Upvotes: 8
Views: 37400
Reputation: 1204
let Decimal = "12.56"
Decimal.substring(Decimal.indexOf(".")+1, Decimal .length)
// answer is 56.
Upvotes: 0
Reputation: 23396
Time to decimals:
function toDec(sec){
var itg=Math.floor(sec);
sec=(sec-itg)*60;
return itg+sec; // OR: return new String(itg+sec);
}
Upvotes: 1
Reputation: 165951
You could use the modulus operator:
var num = 12.1542;
console.log(num % 1);
However, due to the nature of floating point numbers, you will get a number that is very slightly different. For the above example, Chrome gives me 0.15419999999999945
.
Another (slightly longer) option would be to use Math.floor
and then subtract the result from the original number:
var num = 12.1542;
console.log(num - Math.floor(num));
Again, due to the nature of floating point numbers you will end up with a number that is very slightly different than you may expect.
Upvotes: 29
Reputation: 74036
Input sanity checks aside, this should work:
var str = '12.1542';
var value = Math.floor( str ) + ( 60 * (str - Math.floor( str ) ) );
Upvotes: 1
Reputation: 14187
floor is probably the method to get what you want:
http://www.w3schools.com/jsref/jsref_floor.asp
You could also use ceil
http://www.w3schools.com/jsref/jsref_obj_math.asp
Upvotes: 0