manishjangir
manishjangir

Reputation: 1695

get the value after decimal point in 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

Upvotes: 8

Views: 37400

Answers (5)

Kashan Haider
Kashan Haider

Reputation: 1204

let Decimal = "12.56"

Decimal.substring(Decimal.indexOf(".")+1, Decimal .length)

// answer is 56.

Upvotes: 0

Teemu
Teemu

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

James Allardice
James Allardice

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

Sirko
Sirko

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

Nicolas Modrzyk
Nicolas Modrzyk

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

Related Questions