Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get the value after decimal point in javascript

Tags:

javascript

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

like image 604
manishjangir Avatar asked Mar 15 '12 07:03

manishjangir


2 Answers

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.

like image 79
James Allardice Avatar answered Sep 22 '22 08:09

James Allardice


Input sanity checks aside, this should work:

var str = '12.1542';
var value = Math.floor( str ) + ( 60 * (str - Math.floor( str ) ) );
like image 41
Sirko Avatar answered Sep 26 '22 08:09

Sirko