8

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

2
  • 1
    where does this *60 come from? Commented Mar 15, 2012 at 7:45
  • Should the new string be 12.92520 or "12.(1542*60)" (literally)? Commented Mar 15, 2012 at 7:50

5 Answers 5

29

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.

Sign up to request clarification or add additional context in comments.

1 Comment

You can also use toFixed(X) fix the number: console.log((num - Math.floor(num)).toFixed(2));
1

Input sanity checks aside, this should work:

var str = '12.1542';
var value = Math.floor( str ) + ( 60 * (str - Math.floor( str ) ) );

2 Comments

You are missing a closing parenthesis, but if you add it in, this results in 21.251999999999967, which I don't think is what the OP is looking for.
Thx. Added the parenthesis. I think, almost nobody here is completly sure, what the op really wants :-)
1

Time to decimals:

function toDec(sec){
    var itg=Math.floor(sec);
    sec=(sec-itg)*60;
    return itg+sec; // OR: return new String(itg+sec);
}

Comments

0

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

2 Comments

This would get you the part before the decimal point, not after.
0
let Decimal = "12.56"

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

// answer is 56.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.