0

If I have some JS:

 var ct = 1.30;

or it could also be:

 var ct = 0.04;

or it could also be:

 var ct = 4.45677;

How can I simply change these decimals to whole numbers? i.e.:

 30

for the first one

 4

for the second one and

 46

for the 3rd one?

Is there a JS method I can use to do this?

Here is the code I am working with so far. This works fine for seconds, minutes and hours, but I am left without the frames, which is why I started the process in the first place.

  var ct2 = 1.30;

  var timestamp = ct2; 
  var seconds = timestamp % 60;
 timestamp = Math.floor(timestamp / 60);
 var minutes = timestamp % 60;
 timestamp = Math.floor(timestamp / 60);
 var hours = timestamp;

This ends up giving me:

Seconds: 1

Minutes: 0

Hours: 0

But leaves me without this key part:

Frames: 30

9
  • How is it that 1.30 somehow converts to 30 and 0.04 somehow converts to 4? Commented Feb 3, 2015 at 6:16
  • multiply them by 10 and mod them..? what are you trying to do Commented Feb 3, 2015 at 6:17
  • You have to write your own method. There is no direct method available to cater your requirement. Commented Feb 3, 2015 at 6:17
  • You probably want the fractional part rounded upto two decimal places? You'll have to create your own method and deal with the inconsistencies of floating points! Commented Feb 3, 2015 at 6:20
  • @musical_coder: My video player is giving me the see point in the video as a whole number and a decimal, but I have to figure out how to convert this into a timestamp, i.e. 00:00:01:30. So, instead of the decimal .30, I simply need the number to be 30, so I can string the digits together to create the timestamp. I don't really care how it happens, as long as it happens. Commented Feb 3, 2015 at 6:20

1 Answer 1

2

Based on your example numbers given, this function would meet the output requirements you've given. (I'm not sure exactly what it is you're doing, so I called it foo.

var foo = function (num) { 
  num -= Math.trunc(num); 
  num *= 100; 
  return Math.round(num); 
}

Example output:

var ct1 = 0.04, 
    ct2 = 1.30,
    ct3 = 4.45677; 

console.log(foo(ct1)); 
console.log(foo(ct2));
console.log(foo(ct3)); 

>  4
>  30
>  46
Sign up to request clarification or add additional context in comments.

1 Comment

There ya go! That's what I'm talking about. Works like a charm. Thanks for adding the example output as well. Still being a JS newb in many respects, the first part had me a little stumped, but the Example definitely helped me move beyond. Thanks for that.

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.